<template>
  <div class="font-inter bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 text-gray-900 h-screen overflow-hidden flex flex-col"
       :class="{
         'question-fullscreen': isQuestionFullscreen,
         'code-fullscreen': isCodeFullscreen
       }">
    <!-- 题库隐藏/显示切换按钮 -->
    <button 
      id="题库切换按钮" 
      class="toggle-btn"
      :class="sidebarExpanded ? 'toggle-btn-left' : 'toggle-btn-right'"
      @click="toggleSidebar"
    >
      <i class="fa fa-list-ul text-xl"></i>
    </button>

    <!-- 配置保存成功提示 -->
    <div 
      id="save-toast" 
      class="save-toast"
      :class="{ hidden: !showSaveToast }"
    >
      <i class="fa fa-check-circle mr-2"></i>配置已自动保存
    </div>

    <!-- AI助手按钮 -->
    <AIButton 
      :question-id="questionId" 
      session-type="question"
      @toggle="handleAIToggle"
    />

    <!-- AI对话面板 -->
    <AIChatPanel 
      v-if="showAIChat"
      :question-id="questionId"
      session-type="question"
      @close="showAIChat = false"
      @width-change="handleAIWidthChange"
    />


    <!-- 主要内容区 -->
    <main class="flex-1 flex overflow-hidden transition-all duration-300" :style="{ width: showAIChat ? `calc(100% - ${aiPanelWidth}px)` : '100%' }">
      <!-- 左侧题目列表 - 独立滚动区域 -->
      <aside 
        id="sidebar" 
        class="bg-white/95 backdrop-blur-md shadow-2xl fixed h-full z-40 transition-all duration-300 border-r border-white/30"
        :class="sidebarExpanded ? 'sidebar-expanded' : 'sidebar-collapsed'"
      >
        <!-- 搜索区域（固定） -->
        <div class="p-3 border-b border-gray-200/50 bg-white/90 backdrop-blur-sm sticky top-0 z-10">
          <div class="relative">
            <input 
              type="text" 
              placeholder="搜索题目..." 
              class="w-full py-2 pl-8 pr-3 rounded-lg border border-gray-200/50 bg-white/90 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-blue-500/30 focus:border-blue-500 transition-all duration-200 text-sm text-gray-700 placeholder-gray-400"
              v-model="searchQuery"
            >
            <svg class="absolute left-2.5 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
            </svg>
          </div>
        </div>

        <!-- 分类区域（固定） -->
        <div class="p-3 border-b border-gray-200/50 bg-white/90 backdrop-blur-sm sticky top-[60px] z-10">
          <h2 class="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2 flex items-center">
            <svg class="w-3 h-3 mr-1.5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
            </svg>
            题目分类
          </h2>
          <ul class="space-y-1">
            <li>
              <a href="#" class="flex items-center px-2 py-1.5 text-xs font-medium rounded-lg bg-blue-500 text-white hover:bg-blue-600 transition-all duration-200">
                <svg class="w-3 h-3 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"></path>
                </svg>
                全部题目
                <span class="ml-auto bg-white/20 text-white text-xs px-1.5 py-0.5 rounded-full font-semibold">-</span>
              </a>
            </li>
            <li v-for="category in categories" :key="category.id">
              <a href="#" class="flex items-center px-2 py-1.5 text-xs font-medium rounded-lg text-gray-600 hover:bg-gray-100 transition-all duration-200">
                <i :class="`fa ${category.icon} w-3 text-center mr-2`"></i>
                {{ category.name }}
                <span class="ml-auto" :class="category.badgeClass">{{ category.count }}</span>
              </a>
            </li>
          </ul>
        </div>

        <!-- 题目列表（可滚动） -->
        <div class="p-3 pt-3">
          <h2 class="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2 flex items-center">
            <svg class="w-3 h-3 mr-1.5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path>
            </svg>
            题目列表
          </h2>
          <ul class="space-y-1 max-h-[calc(100vh-200px)] overflow-y-auto pr-1">
            <!-- 加载状态 -->
            <li v-if="questionListLoading" class="flex justify-center items-center py-4">
              <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-500"></div>
              <span class="ml-2 text-xs text-gray-500">加载中...</span>
            </li>
            
            <!-- 错误状态 -->
            <li v-else-if="questionListError" class="text-center py-4">
              <div class="text-red-500 text-xs mb-2">{{ questionListError }}</div>
              <button @click="loadQuestionList" class="text-xs text-blue-500 hover:text-blue-700">重试</button>
            </li>
            
            <!-- 题目列表 -->
            <li v-else v-for="(question, index) in questionList" :key="question.id">
              <a 
                href="#" 
                class="flex flex-col px-2 py-2 text-xs font-medium rounded-lg transition-all duration-200"
                :class="question.id === currentQuestion?.id ? 'bg-blue-500 text-white shadow-md' : 'text-gray-600 hover:bg-gray-100'"
                @click="selectQuestion(question)"
              >
                <div class="flex items-center">
                  <span class="w-6 text-center mr-2 font-semibold text-xs">{{ (index + 1).toString().padStart(2, '0') }}</span>
                  <span class="flex-1 truncate">{{ question.title }}</span>
                  <span :class="question.difficultyBadgeClass + ' text-xs px-1.5 py-0.5 rounded-full font-semibold'">{{ question.difficultyText }}</span>
                </div>
                <div class="flex items-center justify-between mt-1 ml-8">
                  <div class="flex items-center space-x-2 text-xs opacity-75">
                    <span>{{ question.submission_count }} 提交</span>
                    <span>{{ question.solution_count }} 完成</span>
                  </div>
                  <div class="text-xs opacity-75">
                    {{ Math.round(question.acceptance_rate * 100) }}%
                  </div>
                </div>
              </a>
            </li>
            
            <!-- 空状态 -->
            <li v-if="!questionListLoading && !questionListError && questionList.length === 0" class="text-center py-4">
              <div class="text-gray-500 text-xs">暂无题目</div>
            </li>
          </ul>
        </div>
      </aside>

      <!-- 分隔线 - 可拖拽 -->
      <div id="sidebar-resizer" class="resize-handle"></div>

      <!-- 中间和右侧内容区 -->
      <div 
        id="main-content" 
        class="flex-1 flex overflow-hidden transition-all duration-300"
        :class="sidebarExpanded ? 'main-content-expanded' : 'main-content-collapsed'"
      >
        <!-- 题目详情区域 - 独立滚动区域 -->
        <div id="problem-area" class="question-detail-section overflow-hidden flex flex-col" :style="{ width: leftPanelWidth + 'px' }">
          <!-- 标签切换（固定） -->
          <div class="flex space-x-1 bg-white/90 backdrop-blur-sm border-b border-gray-200/50 sticky top-0 z-10 p-2" id="tab-container">
            <button 
              class="tab-item px-4 py-2.5 text-sm font-medium rounded-lg transition-all duration-200" 
              name="problem-detail" 
              id="question-btn"
              :class="activeTab === 'detail' ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-md' : 'text-gray-600 hover:bg-gray-100/80 hover:text-gray-800'"
              @click="activeTab = 'detail'"
            >
              题目详情
            </button>
            <button 
              class="tab-item px-4 py-2.5 text-sm font-medium rounded-lg transition-all duration-200" 
              name="submission" 
              id="submission-btn"
              :class="activeTab === 'submission' ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-md' : 'text-gray-600 hover:bg-gray-100/80 hover:text-gray-800'"
              @click="activeTab = 'submission'"
            >
              提交记录
            </button>
            <button 
              class="tab-item px-4 py-2.5 text-sm font-medium rounded-lg transition-all duration-200" 
              name="solution" 
              id="solution-btn"
              :class="activeTab === 'solution' ? 'bg-gradient-to-r from-green-500 to-green-600 text-white shadow-md' : 'text-gray-600 hover:bg-gray-100/80 hover:text-gray-800'"
              @click="activeTab = 'solution'"
            >
              题解
            </button>
            <button 
              class="tab-item px-4 py-2.5 text-sm font-medium rounded-lg transition-all duration-200" 
              name="discussion" 
              id="discussion-btn"
              :class="activeTab === 'discussion' ? 'bg-gradient-to-r from-purple-500 to-purple-600 text-white shadow-md' : 'text-gray-600 hover:bg-gray-100/80 hover:text-gray-800'"
              @click="activeTab = 'discussion'"
            >
              讨论
            </button>
          </div>
          
          <!-- 题目详情（可滚动） -->
          <div v-if="activeTab === 'detail'" class="flex-1 overflow-hidden flex flex-col">
            <!-- 加载状态 -->
            <div v-if="questionLoading" class="flex justify-center items-center py-12">
              <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
              <span class="ml-3 text-gray-600">加载中...</span>
            </div>

            <!-- 错误状态 -->
            <div v-else-if="questionError" class="text-center py-12">
              <div class="text-red-500 mb-4">{{ questionError }}</div>
              <button @click="loadQuestion" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
                重试
              </button>
            </div>

            <!-- 题目内容 -->
            <div v-else-if="currentQuestion" class="flex-1 overflow-hidden flex flex-col">
              <!-- 题目头部（固定） -->
              <div class="bg-white/95 backdrop-blur-sm border-b border-gray-200/50 p-4 sticky top-0 z-10 shadow-sm">
              <div class="flex items-center justify-between">
                <div class="flex items-center space-x-3">
                  <div class="w-8 h-8 bg-blue-500 rounded-lg flex items-center justify-center shadow-sm">
                    <span class="text-white font-bold text-sm">{{ currentQuestionNumber }}</span>
                  </div>
                  <div>
                    <h2 class="text-xl font-bold text-gray-900">{{ currentQuestion.title }}</h2>
                    <div class="flex items-center space-x-3 mt-1">
                      <span 
                        class="px-2 py-1 text-xs font-semibold rounded-lg"
                        :class="currentQuestion.difficulty === 'Easy' ? 'bg-green-100 text-green-800' : 
                                currentQuestion.difficulty === 'Medium' ? 'bg-yellow-100 text-yellow-800' : 
                                'bg-red-100 text-red-800'"
                      >
                        {{ currentQuestion.difficulty === 'Easy' ? '简单' : 
                           currentQuestion.difficulty === 'Medium' ? '中等' : '困难' }}
                      </span>
                      <div class="flex items-center text-gray-500 text-xs">
                        <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"></path>
                        </svg>
                        <span>{{ currentQuestion.submission_count || 0 }} 提交</span>
                      </div>
                      <div class="flex items-center text-gray-500 text-xs">
                        <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"></path>
                        </svg>
                        <span>{{ Math.round((currentQuestion.acceptance_rate || 0) * 100) }}% 通过率</span>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="flex space-x-2">
                  <button 
                    class="p-2 rounded-lg transition-all duration-200"
                    :class="isCodeCompletionDisabled ? 'bg-red-100 text-red-700 hover:bg-red-200' : 'bg-green-100 text-green-700 hover:bg-green-200'"
                    @click="toggleCodeCompletion"
                    :title="isCodeCompletionDisabled ? '启用代码补全' : '禁用代码补全'"
                  >
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path v-if="isCodeCompletionDisabled" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728L5.636 5.636m12.728 12.728L18.364 5.636M5.636 18.364l12.728-12.728"></path>
                      <path v-else stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                  </button>
                  <button 
                    class="p-2 rounded-lg transition-all duration-200"
                    :class="isQuestionFullscreen ? 'bg-blue-100 text-blue-700 hover:bg-blue-200' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'"
                    @click="toggleQuestionFullscreen"
                    :title="isQuestionFullscreen ? '退出全屏' : '题目全屏'"
                  >
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path v-if="!isQuestionFullscreen" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"></path>
                      <path v-else stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 9V4.5M9 9H4.5M9 9L3.5 3.5M15 9h4.5M15 9V4.5M15 9l5.5-5.5M9 15v4.5M9 15H4.5M9 15l-5.5 5.5M15 15h4.5M15 15v4.5m0-4.5l5.5 5.5"></path>
                    </svg>
                  </button>
                  <button 
                    class="px-3 py-1.5 rounded-lg text-xs font-medium transition-all duration-200"
                    :class="currentQuestion.is_favorited ? 'bg-yellow-100 text-yellow-700 hover:bg-yellow-200' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'"
                    @click="toggleFavorite"
                  >
                    <svg class="w-3 h-3 mr-1 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"></path>
                    </svg>
                    {{ currentQuestion.is_favorited ? '已收藏' : '收藏' }}
                  </button>
                  <button class="px-3 py-1.5 bg-gray-100 text-gray-600 hover:bg-gray-200 rounded-lg text-xs font-medium transition-all duration-200">
                    <svg class="w-3 h-3 mr-1 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.367 2.684 3 3 0 00-5.367-2.684z"></path>
                    </svg>
                    分享
                  </button>
                </div>
              </div>
            </div>

            <!-- 题目内容（可滚动） -->
            <div class="flex-1 overflow-y-auto p-4 bg-white/80 backdrop-blur-sm">
              <div class="space-y-4">
                <!-- 题目描述 -->
                <div class="bg-white/90 p-4 rounded-lg border border-gray-200/50 shadow-sm">
                  <h3 class="text-sm font-semibold mb-3 text-gray-800 flex items-center">
                    <svg class="w-4 h-4 mr-2 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                    题目描述
                  </h3>
                  <div class="text-sm text-gray-700 leading-relaxed" v-html="currentQuestion.content">
                  </div>
                </div>

                <!-- 示例 -->
                <div class="bg-white/90 p-4 rounded-lg border border-gray-200/50 shadow-sm" v-if="currentQuestion.sample_input && currentQuestion.sample_output">
                  <h3 class="text-sm font-semibold mb-3 text-gray-800 flex items-center">
                    <svg class="w-4 h-4 mr-2 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"></path>
                    </svg>
                    示例
                  </h3>
                  <div class="space-y-2">
                    <div class="bg-gray-50 p-3 rounded border border-gray-200/50">
                        <div class="text-sm text-gray-700 mb-1">
                          <span class="font-medium text-green-700">输入：</span>
                          <pre class="bg-gray-100 px-2 py-1 rounded text-xs ml-1 mt-1 whitespace-pre-wrap">{{ currentQuestion.sample_input }}</pre>
                        </div>
                        <div class="text-sm text-gray-700">
                          <span class="font-medium text-green-700">输出：</span>
                          <pre class="bg-gray-100 px-2 py-1 rounded text-xs ml-1 mt-1 whitespace-pre-wrap">{{ currentQuestion.sample_output }}</pre>
                        </div>
                    </div>
                  </div>
                </div>

                <!-- 约束条件 -->
                <div class="bg-white/90 p-4 rounded-lg border border-gray-200/50 shadow-sm" v-if="currentQuestion.constraints">
                  <h3 class="text-sm font-semibold mb-3 text-gray-800 flex items-center">
                    <svg class="w-4 h-4 mr-2 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
                    </svg>
                    约束条件
                  </h3>
                  <div class="text-sm text-gray-700 bg-gray-50 p-3 rounded border border-gray-200/50 whitespace-pre-line break-words" v-html="currentQuestion.constraints">
                  </div>
                </div>

                <!-- 输入输出格式 -->
                <div class="bg-white/90 p-4 rounded-lg border border-gray-200/50 shadow-sm" v-if="currentQuestion.input_format || currentQuestion.output_format">
                  <h3 class="text-sm font-semibold mb-3 text-gray-800 flex items-center">
                    <svg class="w-4 h-4 mr-2 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
                    </svg>
                    输入输出格式
                  </h3>
                  <div class="space-y-3">
                    <div v-if="currentQuestion.input_format">
                      <h4 class="text-sm font-medium text-gray-800 mb-1">输入格式：</h4>
                      <div class="text-sm text-gray-700 bg-gray-50 p-3 rounded border border-gray-200/50" v-html="currentQuestion.input_format">
                      </div>
                    </div>
                    <div v-if="currentQuestion.output_format">
                      <h4 class="text-sm font-medium text-gray-800 mb-1">输出格式：</h4>
                      <div class="text-sm text-gray-700 bg-gray-50 p-3 rounded border border-gray-200/50" v-html="currentQuestion.output_format">
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            </div>
          </div>
          
          <!-- 提交记录（可滚动） -->
          <div v-if="activeTab === 'submission'" class="tab-content flex-1 overflow-hidden flex flex-col">
            <!-- 提交记录详情展示区域 -->
            <div v-if="showSubmissionDetail && selectedSubmission" class="flex-1 overflow-y-auto bg-gray-50">
              <div class="max-w-4xl mx-auto p-6">
                <!-- 顶部导航 -->
                <div class="flex items-center justify-between mb-6">
                  <button 
                    @click="closeSubmissionDetail"
                    class="flex items-center space-x-2 text-gray-600 hover:text-gray-800 transition-colors"
                  >
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                    </svg>
                    <span>返回提交列表</span>
                  </button>
                  
                  <div class="text-sm text-gray-500">
                    提交ID: #{{ selectedSubmission.id }}
                  </div>
                </div>

                <!-- 基本信息卡片 -->
                <div class="bg-white rounded-lg shadow-sm border p-6 mb-6">
                  <div class="flex items-center justify-between mb-4">
                    <div class="flex items-center space-x-4">
                      <div :class="getStatusClass(selectedSubmission.status)" class="px-3 py-1 rounded-lg text-sm font-medium">
                        {{ getStatusName(selectedSubmission.status) }}
                      </div>
                      <div class="text-2xl font-bold text-gray-800">{{ selectedSubmission.score || 0 }}分</div>
                    </div>
                    <div class="text-sm text-gray-500">
                      {{ formatTime(selectedSubmission.created_at || selectedSubmission.submitted_at) }}
                    </div>
                  </div>
                  
                  <div class="grid grid-cols-3 gap-6">
                    <div class="text-center">
                      <div class="text-lg font-semibold text-blue-600">{{ selectedSubmission.execution_time || selectedSubmission.time_used || 0 }}ms</div>
                      <div class="text-sm text-gray-500">执行时间</div>
                      <div v-if="selectedSubmission.timeRank" class="text-xs text-gray-400 mt-1">
                        排名: #{{ selectedSubmission.timeRank }}
                      </div>
                    </div>
                    <div class="text-center">
                      <div class="text-lg font-semibold text-green-600">{{ selectedSubmission.memory_used || 0 }}KB</div>
                      <div class="text-sm text-gray-500">内存使用</div>
                      <div v-if="selectedSubmission.memoryRank" class="text-xs text-gray-400 mt-1">
                        排名: #{{ selectedSubmission.memoryRank }}
                      </div>
                    </div>
                    <div class="text-center">
                      <div class="text-lg font-semibold text-gray-800">{{ getLanguageName(selectedSubmission.language) }}</div>
                      <div class="text-sm text-gray-500">编程语言</div>
                    </div>
                  </div>
                  
                  <!-- 排名分布柱形图 -->
                  <div v-if="rankingStats" class="mt-6 pt-6 border-t border-gray-200">
                    <h4 class="text-lg font-semibold text-gray-800 mb-6 flex items-center">
                      <svg class="w-5 h-5 mr-2 text-blue-500" fill="currentColor" viewBox="0 0 24 24">
                        <path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z"/>
                      </svg>
                      排名分布统计
                    </h4>
                    
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                      <!-- 时间排名分布 -->
                      <div class="bg-gradient-to-br from-blue-50 to-indigo-50 rounded-xl p-6 border border-blue-100">
                        <div class="flex items-center mb-4">
                          <div class="w-8 h-8 bg-blue-500 rounded-lg flex items-center justify-center mr-3">
                            <svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 24 24">
                              <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                            </svg>
                          </div>
                          <h5 class="text-lg font-semibold text-gray-800">执行时间排名分布</h5>
                        </div>
                        
                        <div class="space-y-3">
                          <div v-for="(count, index) in (rankingStats.time_distribution || [])" :key="'time-' + index" class="group">
                            <div class="flex items-center justify-between mb-1">
                              <span class="text-sm font-medium text-gray-700">{{ getRankRange(index) }}</span>
                              <span class="text-sm text-gray-500">{{ count }}人</span>
                            </div>
                            <div class="relative">
                              <div class="bg-gray-200 rounded-full h-6 overflow-hidden shadow-inner">
                                <div 
                                  class="bg-gradient-to-r from-blue-400 to-blue-600 h-6 rounded-full transition-all duration-700 ease-out shadow-sm relative"
                                  :style="{ width: rankingStats.total_count > 0 ? `${Math.max((count / rankingStats.total_count) * 100, 2)}%` : '2%' }"
                                >
                                  <div class="absolute inset-0 bg-gradient-to-r from-transparent to-white/20 rounded-full"></div>
                                </div>
                              </div>
                              <!-- 当前位置标记 -->
                              <div v-if="selectedSubmission.timeRank && isInRankRange(selectedSubmission.timeRank, index)" 
                                   class="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full shadow-lg border-2 border-white animate-pulse"></div>
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      <!-- 内存排名分布 -->
                      <div class="bg-gradient-to-br from-green-50 to-emerald-50 rounded-xl p-6 border border-green-100">
                        <div class="flex items-center mb-4">
                          <div class="w-8 h-8 bg-green-500 rounded-lg flex items-center justify-center mr-3">
                            <svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 24 24">
                              <path d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"/>
                            </svg>
                          </div>
                          <h5 class="text-lg font-semibold text-gray-800">内存使用排名分布</h5>
                        </div>
                        
                        <div class="space-y-3">
                          <div v-for="(count, index) in (rankingStats.memory_distribution || [])" :key="'memory-' + index" class="group">
                            <div class="flex items-center justify-between mb-1">
                              <span class="text-sm font-medium text-gray-700">{{ getRankRange(index) }}</span>
                              <span class="text-sm text-gray-500">{{ count }}人</span>
                            </div>
                            <div class="relative">
                              <div class="bg-gray-200 rounded-full h-6 overflow-hidden shadow-inner">
                                <div 
                                  class="bg-gradient-to-r from-green-400 to-green-600 h-6 rounded-full transition-all duration-700 ease-out shadow-sm relative"
                                  :style="{ width: rankingStats.total_count > 0 ? `${Math.max((count / rankingStats.total_count) * 100, 2)}%` : '2%' }"
                                >
                                  <div class="absolute inset-0 bg-gradient-to-r from-transparent to-white/20 rounded-full"></div>
                                </div>
                              </div>
                              <!-- 当前位置标记 -->
                              <div v-if="selectedSubmission.memoryRank && isInRankRange(selectedSubmission.memoryRank, index)" 
                                   class="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full shadow-lg border-2 border-white animate-pulse"></div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    <!-- 图例说明 -->
                    <div class="mt-6 flex items-center justify-center space-x-6 text-sm text-gray-600">
                      <div class="flex items-center">
                        <div class="w-3 h-3 bg-red-500 rounded-full mr-2 animate-pulse"></div>
                        <span>你的排名位置</span>
                      </div>
                      <div class="flex items-center">
                        <div class="w-3 h-3 bg-blue-500 rounded-full mr-2"></div>
                        <span>时间排名</span>
                      </div>
                      <div class="flex items-center">
                        <div class="w-3 h-3 bg-green-500 rounded-full mr-2"></div>
                        <span>内存排名</span>
                      </div>
                    </div>
                  </div>
                  
                </div>

                <!-- 测试用例结果 -->
                <div v-if="selectedSubmission.test_cases || selectedSubmission.passed_cases" class="bg-white rounded-lg shadow-sm border p-6 mb-6">
                  <h3 class="text-lg font-semibold text-gray-800 mb-4">测试用例结果</h3>
                  <div class="flex items-center justify-between">
                    <div class="flex items-center space-x-4">
                      <div class="text-2xl font-bold text-green-600">{{ selectedSubmission.passed_cases || 0 }}</div>
                      <div class="text-gray-400">/</div>
                      <div class="text-2xl font-bold text-gray-600">{{ selectedSubmission.test_cases || 0 }}</div>
                      <div class="text-sm text-gray-500">通过</div>
                    </div>
                    <div class="text-right">
                      <div class="text-lg font-semibold text-green-600">
                        {{ selectedSubmission.test_cases ? Math.round((selectedSubmission.passed_cases || 0) / selectedSubmission.test_cases * 100) : 0 }}%
                      </div>
                      <div class="text-sm text-gray-500">通过率</div>
                    </div>
                  </div>
                  
                  <!-- 进度条 -->
                  <div class="mt-4 w-full bg-gray-200 rounded-full h-2">
                    <div 
                      class="bg-green-500 h-2 rounded-full transition-all duration-500"
                      :style="{ width: selectedSubmission.test_cases ? `${(selectedSubmission.passed_cases || 0) / selectedSubmission.test_cases * 100}%` : '0%' }"
                    ></div>
                  </div>
                </div>

                <!-- 错误信息 -->
                <div v-if="selectedSubmission.error_message" class="bg-white rounded-lg shadow-sm border border-red-200 p-6 mb-6">
                  <h3 class="text-lg font-semibold text-red-600 mb-3">错误信息</h3>
                  <div class="bg-red-50 p-4 rounded-lg">
                    <pre class="text-sm text-red-700 font-mono whitespace-pre-wrap">{{ selectedSubmission.error_message }}</pre>
                  </div>
                </div>

                <!-- 提交代码 -->
                <div class="bg-white rounded-lg shadow-sm border p-6">
                  <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-gray-800">提交代码</h3>
                    <div class="flex items-center space-x-3">
                      <div class="px-2 py-1 bg-gray-100 text-gray-600 text-sm rounded">
                        {{ getLanguageName(selectedSubmission.language) }}
                      </div>
                      <button 
                        @click="copyCode"
                        class="px-3 py-1 bg-blue-500 text-white text-sm rounded hover:bg-blue-600 transition-colors"
                      >
                        复制代码
                      </button>
                      <button 
                        @click="copyToEditor"
                        class="px-3 py-1 bg-green-500 text-white text-sm rounded hover:bg-green-600 transition-colors"
                      >
                        复制到编辑区
                      </button>
                    </div>
                  </div>
                  
                  <div class="bg-white border border-gray-200 text-gray-800 p-4 rounded-lg overflow-x-auto relative">
                    <pre class="text-sm font-mono whitespace-pre-wrap select-all">{{ selectedSubmission.code }}</pre>
                  </div>
                </div>
              </div>
            </div>

            <!-- 提交记录列表 -->
            <div v-else class="flex-1 overflow-hidden flex flex-col">
              <div class="bg-white/90 backdrop-blur-sm p-4 border-b border-gray-200/50 sticky top-0 z-10 shadow-sm">
                <div class="flex justify-between items-center">
                  <div class="flex items-center space-x-3">
                    <div class="w-8 h-8 bg-blue-500 rounded-lg flex items-center justify-center">
                      <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                      </svg>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-900">提交记录</h3>
                  </div>
                  <div class="flex space-x-2">
                    <select class="bg-white/80 backdrop-blur-sm text-sm rounded-lg py-2 px-3 focus:outline-none focus:ring-2 focus:ring-blue-500/30 border border-gray-200/50 shadow-sm" v-model="languageFilter">
                      <option value="all">所有语言</option>
                      <option value="python">Python3</option>
                      <option value="java">Java</option>
                      <option value="cpp">C++</option>
                    </select>
                    <select class="bg-white/80 backdrop-blur-sm text-sm rounded-lg py-2 px-3 focus:outline-none focus:ring-2 focus:ring-blue-500/30 border border-gray-200/50 shadow-sm" v-model="statusFilter">
                      <option value="all">所有状态</option>
                      <option value="ac">通过</option>
                      <option value="wa">解答错误</option>
                      <option value="tle">超时</option>
                    </select>
                  </div>
                </div>
              </div>
              <div class="flex-1 overflow-y-auto p-4 bg-gradient-to-br from-gray-50 to-gray-100/50">
                <!-- 加载状态 -->
                <div v-if="submissionsLoading" class="flex justify-center items-center py-8">
                  <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
                  <span class="ml-2 text-gray-600">加载中...</span>
                </div>
                
                <!-- 错误状态 -->
                <div v-else-if="submissionsError" class="text-center py-8">
                  <div class="text-red-500 mb-2">{{ submissionsError }}</div>
                  <button @click="loadSubmissions" class="text-blue-500 hover:text-blue-600">重试</button>
                </div>
                
                <!-- 空状态 -->
                <div v-else-if="submissions.length === 0" class="text-center py-12">
                  <div class="w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
                    <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                  </div>
                  <h3 class="text-lg font-medium text-gray-900 mb-2">暂无提交记录</h3>
                  <p class="text-gray-500 mb-4">还没有人提交过这道题的代码</p>
                  <button 
                    @click="activeTab = 'detail'" 
                    class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                  >
                    去解题
                  </button>
                </div>
                
                <!-- 提交记录列表 -->
                <div v-else class="space-y-4">
                  <div 
                    class="bg-white/90 backdrop-blur-sm rounded-xl border border-gray-200/50 shadow-sm hover:shadow-md transition-all duration-200"
                    v-for="submission in submissions" 
                    :key="submission.id"
                  >
                    <!-- 提交记录头部 -->
                    <div class="p-4 cursor-pointer" @click="viewSubmissionDetail(submission)">
                      <div class="flex items-center justify-between">
                        <div class="flex items-center space-x-4">
                          <div class="flex items-center space-x-2">
                            <span :class="getStatusClass(submission.status)" class="px-2 py-1 text-xs font-semibold rounded-lg">
                              {{ getStatusName(submission.status) }}
                            </span>
                            <span class="px-2 py-1 bg-gray-100 text-gray-700 text-xs font-medium rounded-lg">
                              {{ getLanguageName(submission.language) }}
                            </span>
                          </div>
                          <div class="text-sm text-gray-500">
                            {{ formatTime(submission.created_at || submission.submitted_at) }}
                          </div>
                        </div>
                        <div class="flex items-center space-x-4 text-sm text-gray-500">
                          <div class="flex items-center space-x-1">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                            <span>{{ submission.execution_time || submission.time_used || 0 }}ms</span>
                          </div>
                          <div class="flex items-center space-x-1">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"></path>
                            </svg>
                            <span>{{ submission.memory_used || 0 }}KB</span>
                          </div>
                          <div class="flex items-center space-x-1">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                            <span>{{ submission.score || 0 }}分</span>
                          </div>
                          <!-- 查看详情图标 -->
                          <div class="flex items-center">
                            <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                            </svg>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          
          <!-- 题解内容（可滚动） -->
          <div v-if="activeTab === 'solution'" class="tab-content flex-1 overflow-hidden flex flex-col">
            <div class="bg-white/90 backdrop-blur-sm p-4 border-b border-gray-200/50 sticky top-0 z-10 shadow-sm">
              <div class="flex justify-between items-center">
                <div class="flex items-center space-x-3">
                  <div class="w-8 h-8 bg-green-500 rounded-lg flex items-center justify-center">
                    <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
                    </svg>
                  </div>
                  <h3 class="text-lg font-semibold text-gray-900">题解</h3>
                </div>
                <button class="px-4 py-2 bg-gradient-to-r from-green-500 to-green-600 text-white text-sm font-medium rounded-lg hover:from-green-600 hover:to-green-700 transition-all duration-200 shadow-sm hover:shadow-md">
                  <svg class="w-4 h-4 mr-2 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                  </svg>
                  发布题解
                </button>
              </div>
            </div>
            <div class="flex-1 overflow-y-auto p-4 bg-gradient-to-br from-gray-50 to-gray-100/50">
              <!-- 加载状态 -->
              <div v-if="solutionsLoading" class="flex justify-center items-center py-8">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-green-500"></div>
                <span class="ml-2 text-gray-600">加载中...</span>
              </div>
              
              <!-- 错误状态 -->
              <div v-else-if="solutionsError" class="text-center py-8">
                <div class="text-red-500 mb-2">{{ solutionsError }}</div>
                <button @click="loadSolutions" class="text-green-500 hover:text-green-600">重试</button>
              </div>
              
              <!-- 空状态 -->
              <div v-else-if="solutions.length === 0" class="text-center py-12">
                <div class="w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
                  <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
                  </svg>
                </div>
                <h3 class="text-lg font-medium text-gray-900 mb-2">暂无题解</h3>
                <p class="text-gray-500 mb-4">还没有人发布过这道题的题解</p>
                <button 
                  @click="activeTab = 'detail'" 
                  class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors"
                >
                  去解题
                </button>
              </div>
              
              <!-- 题解列表 -->
              <div v-else class="space-y-4">
                <div 
                  class="bg-white/90 backdrop-blur-sm rounded-xl border border-gray-200/50 shadow-sm hover:shadow-md transition-all duration-200 cursor-pointer"
                  v-for="solution in solutions"
                  :key="solution.id"
                  @click="viewSolutionDetail(solution)"
                >
                  <div class="p-4">
                    <div class="flex items-center justify-between mb-3">
                      <div class="flex items-center space-x-3">
                        <img :src="solution.user.avatar" alt="用户头像" class="w-10 h-10 rounded-full border-2 border-gray-200">
                        <div>
                          <h4 class="font-semibold text-gray-900">题解 #{{ solution.id }}</h4>
                          <div class="flex items-center text-sm text-gray-500 mt-1">
                            <span class="font-medium">{{ solution.user.username }}</span>
                            <span class="mx-2">·</span>
                            <span>{{ formatTime(solution.created_at) }}</span>
                          </div>
                        </div>
                      </div>
                      <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                      </svg>
                    </div>
                    <p class="text-gray-600 text-sm leading-relaxed line-clamp-2">{{ solution.summary || solution.content.substring(0, 200) + '...' }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 讨论区内容（可滚动） -->
          <div v-if="activeTab === 'discussion'" class="tab-content flex-1 overflow-hidden flex flex-col">
            <div class="bg-white/90 backdrop-blur-sm p-4 border-b border-gray-200/50 sticky top-0 z-10 shadow-sm">
              <div class="flex justify-between items-center">
                <div class="flex items-center space-x-3">
                  <div class="w-8 h-8 bg-purple-500 rounded-lg flex items-center justify-center">
                    <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                    </svg>
                  </div>
                  <h3 class="text-lg font-semibold text-gray-900">讨论区</h3>
                </div>
                <button class="px-4 py-2 bg-gradient-to-r from-purple-500 to-purple-600 text-white text-sm font-medium rounded-lg hover:from-purple-600 hover:to-purple-700 transition-all duration-200 shadow-sm hover:shadow-md">
                  <svg class="w-4 h-4 mr-2 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                  </svg>
                  发起讨论
                </button>
              </div>
            </div>
            <div class="flex-1 overflow-y-auto p-4 bg-gradient-to-br from-gray-50 to-gray-100/50">
              <!-- 加载状态 -->
              <div v-if="discussionsLoading" class="flex justify-center items-center py-8">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500"></div>
                <span class="ml-2 text-gray-600">加载中...</span>
              </div>
              
              <!-- 错误状态 -->
              <div v-else-if="discussionsError" class="text-center py-8">
                <div class="text-red-500 mb-2">{{ discussionsError }}</div>
                <button @click="loadDiscussions" class="text-purple-500 hover:text-purple-600">重试</button>
              </div>
              
              <!-- 空状态 -->
              <div v-else-if="discussions.length === 0" class="text-center py-12">
                <div class="w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
                  <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                  </svg>
                </div>
                <h3 class="text-lg font-medium text-gray-900 mb-2">暂无讨论</h3>
                <p class="text-gray-500 mb-4">还没有人发起过关于这道题的讨论</p>
                <button 
                  @click="activeTab = 'detail'" 
                  class="px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors"
                >
                  去解题
                </button>
              </div>
              
              <!-- 讨论列表 -->
              <div v-else class="space-y-4">
                <div 
                  class="bg-white/90 backdrop-blur-sm rounded-xl border border-gray-200/50 shadow-sm hover:shadow-md transition-all duration-200 cursor-pointer"
                  v-for="discussion in discussions"
                  :key="discussion.id"
                  @click="viewDiscussionDetail(discussion)"
                >
                  <div class="p-4">
                    <div class="flex items-start justify-between mb-3">
                      <div class="flex items-center space-x-3">
                        <img :src="discussion.author.avatar" alt="用户头像" class="w-10 h-10 rounded-full border-2 border-gray-200">
                        <div>
                          <h4 class="font-semibold text-gray-900">{{ discussion.title }}</h4>
                          <div class="flex items-center text-sm text-gray-500 mt-1">
                            <span class="font-medium">{{ discussion.author.username }}</span>
                            <span class="mx-2">·</span>
                            <span>{{ formatTime(discussion.created_at) }}</span>
                            <span class="mx-2">·</span>
                            <span>{{ discussion.view_count }} 次浏览</span>
                          </div>
                        </div>
                      </div>
                      <div class="flex items-center space-x-2">
                        <span v-if="discussion.is_pinned" class="px-2 py-1 bg-yellow-100 text-yellow-800 text-xs font-medium rounded-full">
                          置顶
                        </span>
                        <svg class="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                        </svg>
                      </div>
                    </div>
                    <p class="text-gray-600 text-sm leading-relaxed line-clamp-2">{{ discussion.summary || discussion.content.substring(0, 200) + '...' }}</p>
                    <div class="flex items-center justify-between mt-3">
                      <div class="flex items-center space-x-4 text-xs text-gray-500">
                        <span class="flex items-center">
                          <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                          </svg>
                          {{ discussion.like_count }}
                        </span>
                        <span class="flex items-center">
                          <svg class="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                          </svg>
                          评论
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分隔线 - 可拖拽 (垂直方向) -->
        <div class="resize-handle" id="resize-handle" @mousedown="resizeStart"></div>

        <!-- 代码编辑区域 - 独立滚动区域 -->
        <div id="editor-area" class="code-editor-section overflow-hidden flex flex-col bg-white text-gray-900 flex-1">
          <!-- 代码编辑器工具栏（固定） -->
          <div class="border-b border-gray-200/50 p-3 flex justify-between items-center sticky top-0 z-10 bg-white/95 backdrop-blur-sm shadow-sm">
            <div class="flex items-center space-x-3 flex-shrink-0">
              <div class="w-6 h-6 bg-green-500 rounded-lg flex items-center justify-center">
                <svg class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"></path>
                </svg>
              </div>
              <h3 class="text-sm font-semibold text-gray-900 whitespace-nowrap">代码编辑器</h3>
              <!-- AI补全状态提示 -->
              <div v-if="aiCompletionLoading" class="flex items-center space-x-1">
                <div class="w-2 h-2 bg-blue-400 rounded-full animate-pulse"></div>
                <span class="text-xs text-blue-600 whitespace-nowrap">思考中...</span>
              </div>
              <div v-else-if="isSubmitting" class="flex items-center space-x-1">
                <div class="w-2 h-2 bg-gray-400 rounded-full"></div>
                <span class="text-xs text-gray-600 whitespace-nowrap">提交中，AI补全已禁用</span>
              </div>
              <div v-else-if="!submissions || submissions.length === 0" class="flex items-center space-x-1">
                <div class="w-2 h-2 bg-orange-400 rounded-full"></div>
                <span class="text-xs text-orange-600 whitespace-nowrap">AI补全已禁用</span>
              </div>
              <div v-else class="flex items-center space-x-1">
                <div class="w-2 h-2 rounded-full" :class="isCodeCompletionDisabled ? 'bg-red-400' : 'bg-green-400'"></div>
                <span class="text-xs whitespace-nowrap" :class="isCodeCompletionDisabled ? 'text-red-600' : 'text-green-600'">
                  {{ isCodeCompletionDisabled ? 'AI补全已禁用' : 'AI补全已启用' }}
                </span>
              </div>
            </div>
            <div class="flex items-center space-x-3 flex-shrink-0">
              <div class="flex items-center space-x-2">
                <label class="text-xs text-gray-600 whitespace-nowrap">语言:</label>
                <div class="relative" ref="languageMenuRef">
                  <button 
                    class="language-selector bg-white text-xs rounded-lg py-1 px-2 focus:outline-none focus:ring-1 focus:ring-blue-500/30 border border-gray-200/50 flex items-center justify-between w-24"
                    @click="isLanguageMenuOpen = !isLanguageMenuOpen"
                  >
                    {{ getLanguageName(selectedLanguage) }}
                    <svg class="w-3 h-3 ml-1 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                    </svg>
                  </button>
                  <ul 
                    v-show="isLanguageMenuOpen" 
                    class="absolute mt-1 w-32 bg-white border border-gray-200 rounded-lg shadow-md z-50"
                    @mouseleave="isLanguageMenuOpen = false"
                  >
                    <li class="px-3 py-1.5 text-sm text-gray-700 hover:bg-blue-500 hover:text-white cursor-pointer" @click="selectLanguageOption('python')">Python3</li>
                    <li class="px-3 py-1.5 text-sm text-gray-700 hover:bg-blue-500 hover:text-white cursor-pointer" @click="selectLanguageOption('java')">Java</li>
                    <li class="px-3 py-1.5 text-sm text-gray-700 hover:bg-blue-500 hover:text-white cursor-pointer" @click="selectLanguageOption('cpp')">C++</li>
                  </ul>
                </div>
              </div>
              <div class="flex items-center space-x-2">
                <label class="text-xs text-gray-600 whitespace-nowrap">主题:</label>
                <div class="relative" ref="themeMenuRef">
                  <button 
                    class="theme-selector bg-white text-xs rounded-lg py-1 px-2 focus:outline-none focus:ring-1 focus:ring-blue-500/30 border border-gray-200/50 flex items-center justify-between w-28"
                    @click="isThemeMenuOpen = !isThemeMenuOpen"
                  >
                    {{ selectedThemeLabel }}
                    <svg class="w-3 h-3 ml-1 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                    </svg>
                  </button>
                  <ul 
                    v-show="isThemeMenuOpen" 
                    class="absolute mt-1 w-36 bg-white border border-gray-200 rounded-lg shadow-md z-50"
                    @mouseleave="isThemeMenuOpen = false"
                  >
                    <li class="px-3 py-1.5 text-sm text-gray-700 hover:bg-blue-500 hover:text-white cursor-pointer" @click="selectThemeOption('dracula')">Dracula</li>
                    <li class="px-3 py-1.5 text-sm text-gray-700 hover:bg-blue-500 hover:text-white cursor-pointer" @click="selectThemeOption('monokai')">Monokai</li>
                    <li class="px-3 py-1.5 text-sm text-gray-700 hover:bg-blue-500 hover:text-white cursor-pointer" @click="selectThemeOption('eclipse')">Eclipse</li>
                    <li class="px-3 py-1.5 text-sm text-gray-700 hover:bg-blue-500 hover:text-white cursor-pointer" @click="selectThemeOption('solarized light')">Solarized Light</li>
                    <li class="px-3 py-1.5 text-sm text-gray-700 hover:bg-blue-500 hover:text-white cursor-pointer" @click="selectThemeOption('solarized dark')">Solarized Dark</li>
                  </ul>
                </div>
              </div>
            </div>
            <div class="flex items-center space-x-2">
              <button 
                class="p-2 rounded-lg transition-all duration-200"
                :class="isCodeFullscreen ? 'bg-blue-100 text-blue-700 hover:bg-blue-200' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'"
                @click="toggleCodeFullscreen"
                :title="isCodeFullscreen ? '退出全屏' : '代码全屏'"
              >
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path v-if="!isCodeFullscreen" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"></path>
                  <path v-else stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 9V4.5M9 9H4.5M9 9L3.5 3.5M15 9h4.5M15 9V4.5M15 9l5.5-5.5M9 15v4.5M9 15H4.5M9 15l-5.5 5.5M15 15h4.5M15 15v4.5m0-4.5l5.5 5.5"></path>
                </svg>
              </button>
              <button class="px-3 py-1.5 bg-gray-100 text-gray-600 hover:bg-gray-200 rounded-lg text-xs font-medium transition-all duration-200" @click="resetCode">
                <svg class="w-3 h-3 mr-1 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                </svg>
                重置
              </button>
              <button 
                class="px-3 py-1.5 text-white rounded-lg text-xs font-medium transition-all duration-200"
                :class="isRunning ? 'bg-gray-400 cursor-not-allowed' : 'bg-green-500 hover:bg-green-600'"
                :disabled="isRunning"
                @click="runCode"
              >
                <svg class="w-3 h-3 mr-1 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h1m4 0h1m-6 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                {{ isRunning ? '运行中...' : '运行' }}
              </button>
              <button 
                class="px-3 py-1.5 text-white rounded-lg text-xs font-medium transition-all duration-200"
                :class="isSubmitting ? 'bg-gray-400 cursor-not-allowed' : 'bg-blue-500 hover:bg-blue-600'"
                :disabled="isSubmitting"
                @click="submitCode"
              >
                <svg class="w-3 h-3 mr-1 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>
                </svg>
                {{ isSubmitting ? '提交中...' : '提交' }}
              </button>
            </div>
          </div>
          
          <!-- 代码编辑器（可滚动） -->
          <div class="flex-1 overflow-hidden code-editor-container relative" ref="editorContainer">
            <!-- AI代码补全组件 -->
            <CodeCompletion
              :code="currentCode"
              :language="selectedLanguage"
              :question-id="questionId"
              :has-submitted="hasSubmitted"
              :is-contest="false"
              :show-a-i-chat="showAIChat"
              :ai-panel-width="aiPanelWidth"
              :current-position="getCurrentLineContent()"
              :is-disabled="isCodeCompletionDisabled"
              @apply="applyCodeCompletion"
            />
          </div>

          <!-- 水平分隔线 - 可拖拽调整编辑器和输出区域高度 -->
          <div class="resize-handle-horizontal" id="resize-handle-editor" @mousedown="resizeStartEditor"></div>

          <!-- 运行结果区域 -->
          <div class="output-section border-t border-gray-200/50 bg-white/95 backdrop-blur-sm shadow-sm" :style="{ height: outputAreaHeight + 'px' }">
            <div class="flex border-b border-gray-200/50 p-2">
              <div class="flex items-center space-x-2">
                <div class="w-5 h-5 bg-blue-500 rounded flex items-center justify-center">
                  <svg class="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                  </svg>
            </div>
                <h3 class="text-sm font-semibold text-gray-900">运行结果</h3>
            </div>
              <div class="flex space-x-1 ml-auto">
                <button class="px-2 py-1 text-xs font-medium rounded bg-blue-500 text-white hover:bg-blue-600 transition-all duration-200">
                  输出
                </button>
                <button class="px-2 py-1 text-xs font-medium rounded text-gray-600 hover:bg-gray-100 transition-all duration-200">
                  错误
                </button>
              </div>
            </div>
            <div class="p-4 h-[calc(100%-40px)] overflow-y-auto bg-gradient-to-br from-gray-50 to-gray-100/50">
              <!-- 测试用例卡片区域 -->
              <div class="bg-white/90 backdrop-blur-sm p-4 rounded-xl border border-blue-200/50 shadow-lg mb-3">
                <div class="flex items-center justify-between mb-3">
                  <div class="flex items-center space-x-3">
                    <div class="w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center">
                      <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                      </svg>
                    </div>
                    <div>
                      <span class="text-sm font-semibold text-blue-700">测试用例</span>
                      <p class="text-xs text-blue-600">管理您的测试用例</p>
                    </div>
                  </div>
                  <button 
                    @click="isAddingTestCase = true" 
                    class="px-3 py-1 text-xs font-medium rounded bg-green-500 text-white hover:bg-green-600 transition-all duration-200 flex items-center space-x-1"
                  >
                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                    </svg>
                    <span>添加测试用例</span>
                  </button>
                </div>

                <!-- 测试用例卡片列表 -->
                <div class="flex space-x-2 mb-3 overflow-x-auto pb-2">
                  <div 
                    v-for="(testCase, index) in testCases" 
                    :key="testCase.id"
                    @click="switchTestCase(index)"
                    :class="[
                      'flex-shrink-0 px-3 py-2 rounded-lg cursor-pointer transition-all duration-200 border-2',
                      activeTestCaseIndex === index 
                        ? 'bg-blue-500 text-white border-blue-500' 
                        : 'bg-gray-100 text-gray-700 border-gray-200 hover:bg-gray-200'
                    ]"
                  >
                    <div class="flex items-center space-x-2">
                      <!-- 状态图标 -->
                      <div v-if="testCase.status === 'running'" class="w-3 h-3">
                        <div class="w-3 h-3 border-2 border-current border-t-transparent rounded-full animate-spin"></div>
                      </div>
                      <div v-else-if="testCase.status === 'success'" class="w-3 h-3 bg-green-500 rounded-full flex items-center justify-center">
                        <svg class="w-2 h-2 text-white" fill="currentColor" viewBox="0 0 20 20">
                          <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"></path>
                        </svg>
                      </div>
                      <div v-else-if="testCase.status === 'error'" class="w-3 h-3 bg-red-500 rounded-full flex items-center justify-center">
                        <svg class="w-2 h-2 text-white" fill="currentColor" viewBox="0 0 20 20">
                          <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
                        </svg>
                      </div>
                      <div v-else class="w-3 h-3 bg-gray-400 rounded-full"></div>
                      
                      <!-- 测试用例名称 -->
                      <span class="text-xs font-medium">{{ testCase.name }}</span>
                      
                      <!-- 删除按钮 -->
                      <button 
                        v-if="testCase.id !== 'sample' && testCase.id !== 'custom'"
                        @click.stop="removeTestCase(index)"
                        class="ml-1 w-4 h-4 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 transition-colors"
                      >
                        <svg class="w-2 h-2" fill="currentColor" viewBox="0 0 20 20">
                          <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
                        </svg>
                      </button>
                    </div>
                  </div>
                </div>

                <!-- 添加测试用例表单 -->
                <div v-if="isAddingTestCase" class="bg-gray-50 p-3 rounded-lg border border-gray-200 mb-3">
                  <div class="space-y-3">
                    <div>
                      <label class="block text-xs font-medium text-gray-700 mb-1">测试用例名称：</label>
                      <input 
                        v-model="newTestCaseName" 
                        placeholder="例如：边界测试"
                        class="w-full p-2 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      />
                    </div>
                    <div>
                      <label class="block text-xs font-medium text-gray-700 mb-1">输入数据：</label>
                      <textarea 
                        v-model="newTestCaseInput" 
                        placeholder="请输入测试数据"
                        class="w-full h-16 p-2 border border-gray-300 rounded text-sm resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      ></textarea>
                    </div>
                    <div class="flex space-x-2">
                      <button 
                        @click="addTestCase" 
                        class="px-3 py-1 text-xs font-medium rounded bg-blue-500 text-white hover:bg-blue-600 transition-all duration-200"
                      >
                        添加
                      </button>
                      <button 
                        @click="cancelAddTestCase" 
                        class="px-3 py-1 text-xs font-medium rounded bg-gray-500 text-white hover:bg-gray-600 transition-all duration-200"
                      >
                        取消
                      </button>
                    </div>
                  </div>
                </div>

                <!-- 当前测试用例输入区域 -->
                <div v-if="testCases[activeTestCaseIndex]">
                  <label class="block text-sm font-medium text-gray-700 mb-1">输入数据：</label>
                  <textarea 
                    v-model="customInput" 
                    :placeholder="`请输入${testCases[activeTestCaseIndex].name}的测试数据`"
                    class="w-full h-20 p-3 border border-gray-300 rounded-lg font-mono text-sm resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  ></textarea>
                </div>
              </div>

              <!-- 当前测试用例结果 -->
              <div v-if="testCases[activeTestCaseIndex]" class="bg-white/90 backdrop-blur-sm p-4 rounded-xl border shadow-lg mb-3">
                <!-- 测试用例标题 -->
                <div class="flex items-center justify-between mb-3">
                  <div class="flex items-center space-x-3">
                    <div class="w-6 h-6 rounded-full flex items-center justify-center"
                         :class="{
                           'bg-green-500': testCases[activeTestCaseIndex].status === 'success',
                           'bg-red-500': testCases[activeTestCaseIndex].status === 'error',
                           'bg-blue-500': testCases[activeTestCaseIndex].status === 'running',
                           'bg-gray-400': testCases[activeTestCaseIndex].status === 'pending'
                         }">
                      <!-- 成功图标 -->
                      <svg v-if="testCases[activeTestCaseIndex].status === 'success'" class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                      </svg>
                      <!-- 错误图标 -->
                      <svg v-else-if="testCases[activeTestCaseIndex].status === 'error'" class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                      </svg>
                      <!-- 运行中图标 -->
                      <div v-else-if="testCases[activeTestCaseIndex].status === 'running'" class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                      <!-- 等待图标 -->
                      <svg v-else class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                      </svg>
                    </div>
                    <div>
                      <span class="text-sm font-semibold" 
                            :class="{
                              'text-green-700': testCases[activeTestCaseIndex].status === 'success',
                              'text-red-700': testCases[activeTestCaseIndex].status === 'error',
                              'text-blue-700': testCases[activeTestCaseIndex].status === 'running',
                              'text-gray-600': testCases[activeTestCaseIndex].status === 'pending'
                            }">
                        {{ testCases[activeTestCaseIndex].name }} - 
                        <span v-if="testCases[activeTestCaseIndex].status === 'success'">执行成功</span>
                        <span v-else-if="testCases[activeTestCaseIndex].status === 'error'">执行错误</span>
                        <span v-else-if="testCases[activeTestCaseIndex].status === 'running'">正在运行</span>
                        <span v-else>等待执行</span>
                      </span>
                      <p class="text-xs" 
                         :class="{
                           'text-green-600': testCases[activeTestCaseIndex].status === 'success',
                           'text-red-600': testCases[activeTestCaseIndex].status === 'error',
                           'text-blue-600': testCases[activeTestCaseIndex].status === 'running',
                           'text-gray-500': testCases[activeTestCaseIndex].status === 'pending'
                         }">
                        <span v-if="testCases[activeTestCaseIndex].status === 'success'">代码运行完成，无错误</span>
                        <span v-else-if="testCases[activeTestCaseIndex].status === 'error'">代码运行时发生错误</span>
                        <span v-else-if="testCases[activeTestCaseIndex].status === 'running'">代码执行中，请稍候...</span>
                        <span v-else>请点击运行按钮执行代码</span>
                      </p>
                    </div>
                  </div>
                </div>

                <!-- 输入数据 -->
                <div v-if="testCases[activeTestCaseIndex].input" class="mb-3">
                  <label class="block text-xs font-medium text-gray-600 mb-1">输入：</label>
                  <div class="bg-gray-100 p-2 rounded text-sm font-mono">
                    <pre class="whitespace-pre-wrap">{{ testCases[activeTestCaseIndex].input }}</pre>
                  </div>
                </div>

                <!-- 输出结果 -->
                <div v-if="testCases[activeTestCaseIndex].result" class="mb-3">
                  <label class="block text-xs font-medium text-gray-600 mb-1">输出：</label>
                  <div class="bg-gray-900 text-green-400 p-3 rounded-lg font-mono text-sm overflow-x-auto">
                    <pre class="whitespace-pre-wrap">{{ testCases[activeTestCaseIndex].result }}</pre>
                  </div>
                </div>

                <!-- 错误信息 -->
                <div v-if="testCases[activeTestCaseIndex].error" class="mb-3">
                  <label class="block text-xs font-medium text-gray-600 mb-1">错误：</label>
                  <div class="bg-gray-900 text-red-400 p-3 rounded-lg font-mono text-sm overflow-x-auto">
                    <pre class="whitespace-pre-wrap">{{ testCases[activeTestCaseIndex].error }}</pre>
                  </div>
                </div>

                <!-- 等待状态提示 -->
                <div v-if="testCases[activeTestCaseIndex].status === 'pending'" class="bg-gray-100 p-3 rounded-lg">
                  <p class="text-gray-500 text-sm">点击"运行"按钮来测试您的代码</p>
                </div>

                <!-- 运行中状态提示 -->
                <div v-if="testCases[activeTestCaseIndex].status === 'running'" class="bg-gray-100 p-3 rounded-lg">
                  <p class="text-gray-500 text-sm">正在执行您的代码，请耐心等待</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>

</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {useQuestionStore} from '@/stores/question';
// import type { Question } from '@/types';
import { executionApi } from '@/api/execution';
import { submissionApi } from '@/api/submission';
import { solutionApi } from '@/api/solution';
import { aiApi } from '@/api/ai';
import { questionApi } from '@/api/question';
import AIButton from '@/components/AI/AIButton.vue';
import AIChatPanel from '@/components/AI/AIChatPanel.vue';
import CodeCompletion from '@/components/AI/CodeCompletion.vue';
import { discussionApi } from '@/api/discussion';
import CodeMirror from 'codemirror';
// 核心依赖导入
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/dracula.css';
import 'codemirror/theme/monokai.css';
import 'codemirror/theme/eclipse.css';
import 'codemirror/theme/solarized.css';
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/addon/hint/show-hint';
import 'codemirror/mode/python/python';
import 'codemirror/mode/clike/clike';
import 'codemirror/addon/edit/closebrackets';

// 状态管理
const sidebarExpanded = ref(false);
const showSaveToast = ref(false);
const showAIChat = ref(false);
const hasSubmitted = ref(false);
const currentCode = ref('');
const aiPanelWidth = ref(400);
const selectedTheme = ref('dracula');
const searchQuery = ref('');
const activeTab = ref('detail');
const selectedLanguage = ref('cpp'); // 默认值，但会在mounted时被覆盖
const languageFilter = ref('all');
const statusFilter = ref('all');
const runOutput = ref('');
const runError = ref('');
const isRunning = ref(false);
const isSubmitting = ref(false);
const customInput = ref('');
const currentSubmission = ref(null);
const isLanguageMenuOpen = ref(false);
const selectLanguageOption = (lang) => {
  selectedLanguage.value = lang;
  changeLanguage();
  isLanguageMenuOpen.value = false;
};

// 主题下拉菜单状态与选择处理
const isThemeMenuOpen = ref(false);
const selectedThemeLabel = computed(() => {
  switch (selectedTheme.value) {
    case 'dracula': return 'Dracula';
    case 'monokai': return 'Monokai';
    case 'eclipse': return 'Eclipse';
    case 'solarized light': return 'Solarized Light';
    case 'solarized dark': return 'Solarized Dark';
    default: return selectedTheme.value;
  }
});
const selectThemeOption = (theme) => {
  selectedTheme.value = theme;
  changeTheme();
  isThemeMenuOpen.value = false;
};

// 测试用例相关
const testCases = ref([]);
const activeTestCaseIndex = ref(0);
const isAddingTestCase = ref(false);
const newTestCaseInput = ref('');
const newTestCaseName = ref('');
const autoSaveInterval = ref(null);
const lastSavedCode = ref('');
const lastSavedLanguage = ref('cpp'); // 记录上次保存的语言
const customCompletions = ref([]); // 补全项列表
const editorContainer = ref(null);
let editor = null; // 编辑器实例

// 下拉菜单容器引用，用于外部点击关闭
const languageMenuRef = ref(null);
const themeMenuRef = ref(null);

// 全局点击关闭下拉菜单
const handleGlobalClick = (e) => {
  const target = e.target;
  if (isLanguageMenuOpen.value) {
    const el = languageMenuRef.value;
    if (el && !el.contains(target)) {
      isLanguageMenuOpen.value = false;
    }
  }
  if (isThemeMenuOpen.value) {
    const el = themeMenuRef.value;
    if (el && !el.contains(target)) {
      isThemeMenuOpen.value = false;
    }
  }
};

onMounted(() => {
  document.addEventListener('click', handleGlobalClick);
});

onUnmounted(() => {
  document.removeEventListener('click', handleGlobalClick);
});

// AI补全相关
const aiCompletion = ref(''); // AI生成的补全内容
const showAICompletion = ref(false); // 是否显示AI补全
const aiCompletionLoading = ref(false); // AI补全加载状态
const lastCompletionRequest = ref(''); // 上次请求的代码，用于避免重复请求
const aiCompletionMarker = ref(null); // AI补全的编辑器标记
const aiCompletionWidget = ref(null); // AI补全的编辑器小部件
const aiCompletionTimeout = ref(null); // AI补全的防抖定时器
const lastCompletionTime = ref(0); // 上次补全请求的时间戳
const isUserTyping = ref(false); // 用户是否正在输入
const isCodeCompletionDisabled = ref(false); // 是否禁用代码补全

// 全屏状态管理
const isQuestionFullscreen = ref(false);
const isCodeFullscreen = ref(false);

// 详情显示状态管理
const selectedSubmission = ref(null);
const selectedSolution = ref(null);
const showSubmissionDetail = ref(false);
const showSolutionDetail = ref(false);
const rankingStats = ref(null);

// 提交记录数据
const submissions = ref([]);
const submissionsLoading = ref(false);
const submissionsError = ref('');

// 题解数据
const solutions = ref([]);
const solutionsLoading = ref(false);
const solutionsError = ref('');

// 讨论区数据
const discussions = ref([]);
const discussionsLoading = ref(false);
const discussionsError = ref('');

const questionStore = useQuestionStore();

// 题目数据从API获取
const currentQuestion = ref(null);
const questionLoading = ref(false);
const questionError = ref('');

// 获取路由参数
const route = useRoute();
const router = useRouter();
const questionId = computed(() => parseInt(route.params.id));

// 加载题目详情
const loadQuestion = async (skipInitEditor = false) => {
  if (!questionId.value) return;
  
  try {
    questionLoading.value = true;
    questionError.value = '';
    
    const question = await questionStore.fetchQuestion(questionId.value);
    if (question) {
      currentQuestion.value = question;
      // 初始化测试用例
      initializeTestCases(question);
      // 初始化代码编辑器（可跳过，避免提交后重置代码）
      if (!skipInitEditor) {
        initializeCodeEditor();
      }
    } else {
      questionError.value = '题目不存在或加载失败';
    }
  } catch (error) {
    console.error('加载题目失败:', error);
    questionError.value = '网络错误，请检查网络连接';
  } finally {
    questionLoading.value = false;
  }
};

// 语言关键字定义
const languageKeywords = ref({
  python: [
    'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue',
    'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',
    'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass',
    'raise', 'return', 'try', 'while', 'with', 'yield'
  ],
  java: [
    'abstract', 'assert', 'boolean', 'break', 'byte', 'case', 'catch', 'char',
    'class', 'const', 'continue', 'default', 'do', 'double', 'else', 'enum',
    'extends', 'final', 'finally', 'float', 'for', 'if', 'implements', 'import',
    'instanceof', 'int', 'interface', 'long', 'native', 'new', 'package',
    'private', 'protected', 'public', 'return', 'short', 'static', 'strictfp',
    'super', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient',
    'try', 'void', 'volatile', 'while'
  ],
  cpp: [
    'alignas', 'alignof', 'and', 'and_eq', 'asm', 'auto', 'bitand', 'bitor',
    'bool', 'break', 'case', 'catch', 'char', 'char8_t', 'char16_t', 'char32_t',
    'class', 'compl', 'concept', 'const', 'consteval', 'constexpr', 'const_cast',
    'continue', 'co_await', 'co_return', 'co_yield', 'decltype', 'default',
    'delete', 'do', 'double', 'dynamic_cast', 'else', 'enum', 'explicit',
    'export', 'extern', 'false', 'float', 'for', 'friend', 'goto', 'if',
    'inline', 'int', 'long', 'mutable', 'namespace', 'new', 'noexcept', 'not',
    'not_eq', 'nullptr', 'operator', 'or', 'or_eq', 'private', 'protected',
    'public', 'register', 'reinterpret_cast', 'requires', 'return', 'short',
    'signed', 'sizeof', 'static', 'static_assert', 'static_cast', 'struct',
    'switch', 'template', 'this', 'thread_local', 'throw', 'true', 'try',
    'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using', 'virtual',
    'void', 'volatile', 'wchar_t', 'while', 'xor', 'xor_eq'
  ]
});

// 拖动相关逻辑
let leftPanelWidth = ref(500);
const isResizingEditor = ref(false);
const startY = ref(0);
const editorArea = ref(null);
const resizerEditor = ref(null);
const outputAreaHeight = ref(300);
const isResizing = ref(false);
const startX = ref(0);
const leftPanel = ref(null);
const resizerQuestion = ref(null);



function resizeStart(e) {
  e.preventDefault();
  isResizing.value = true;
  startX.value = e.clientX;
  leftPanel.value = document.getElementById('problem-area');
  resizerQuestion.value = document.getElementById('resize-handle');
  document.body.style.cursor = 'ew-resize';
  resizerQuestion.value.classList.add('bg-blue-200');
  document.body.style.userSelect = 'none';
  document.addEventListener('mousemove', resizeMove);
  document.addEventListener('mouseup', resizeEnd);
}

function resizeMove(e) {
  if (!isResizing.value || !leftPanel.value) return;
  const containerWidth = leftPanel.value.parentElement.offsetWidth;
  const newWidth = leftPanelWidth.value + (e.clientX - startX.value);
  if (newWidth >= 300 && newWidth <= containerWidth - 300) {
    leftPanelWidth.value = newWidth;
    startX.value = e.clientX;
  }
}

function resizeEnd() {
  isResizing.value = false;
  document.removeEventListener('mousemove', resizeMove);
  document.removeEventListener('mouseup', resizeEnd);
  document.body.style.cursor = '';
  if (resizerQuestion.value) {
    resizerQuestion.value.classList.remove('bg-blue-200');
  }
  document.body.style.userSelect = '';
}

function resizeStartEditor(e) {
  e.preventDefault();
  isResizingEditor.value = true;
  startY.value = e.clientY;
  editorArea.value = document.getElementById('editor-area');
  resizerEditor.value = document.getElementById('resize-handle-editor');
  document.body.style.cursor = 'ns-resize';
  resizerEditor.value.classList.add('bg-blue-200');
  document.body.style.userSelect = 'none';
  document.addEventListener('mousemove', resizeMoveEditor);
  document.addEventListener('mouseup', resizeEndEditor);
}

function resizeMoveEditor(e) {
  if (!isResizingEditor.value || !editorArea.value) return;
  const containerHeight = editorArea.value.offsetHeight;
  const newHeight = outputAreaHeight.value + (startY.value - e.clientY);
  if (newHeight >= 100 && newHeight <= containerHeight - 200) {
    outputAreaHeight.value = newHeight;
    startY.value = e.clientY;
  }
}

function resizeEndEditor() {
  isResizingEditor.value = false;
  document.removeEventListener('mousemove', resizeMoveEditor);
  document.removeEventListener('mouseup', resizeEndEditor);
  document.body.style.cursor = '';
  if (resizerEditor.value) {
    resizerEditor.value.classList.remove('bg-blue-200');
  }
  document.body.style.userSelect = '';
}

// 本地存储与自动保存
function getStorageKey() {
  // 生成唯一键：题目ID + 语言类型
  return `code_${questionId.value}_${selectedLanguage.value}`;
}

// 新增：获取全局设置的存储键
function getGlobalSettingsKey() {
  return 'code_editor_global_settings';
}

// 新增：保存全局设置（包括当前选择的语言）
function saveGlobalSettings() {
  try {
    const settings = {
      lastUsedLanguage: selectedLanguage.value,
      lastUsedTheme: selectedTheme.value,
      savedAt: new Date().toISOString()
    };
    localStorage.setItem(getGlobalSettingsKey(), JSON.stringify(settings));
  } catch (error) {
    console.error('保存全局设置失败:', error);
  }
}

// 新增：加载全局设置
function loadGlobalSettings() {
  try {
    const settingsData = localStorage.getItem(getGlobalSettingsKey());
    if (settingsData) {
      return JSON.parse(settingsData);
    }
  } catch (error) {
    console.error('加载全局设置失败:', error);
  }
  return null;
}

function loadSavedCode() {
  try {
    const storageKey = getStorageKey();
    const savedData = localStorage.getItem(storageKey);
    
    if (savedData) {
      const data = JSON.parse(savedData);
      return data;
    } else {
      return null;
    }
  } catch (error) {
    console.error('加载代码失败:', error);
    return null;
  }
}


function autoSave() {
  if (!editor) return;
  
  const currentCode = editor.getValue();
  const currentLang = selectedLanguage.value;
  const theme = editor.getOption('theme');
  const languageMode = editor.getOption('mode');

  // 仅当代码或语言变化时才保存
  if (currentCode !== lastSavedCode.value || currentLang !== lastSavedLanguage.value) {
    try {
      const storageKey = getStorageKey();
      const saveData = {
        questionId: questionId.value,
        language: currentLang,
        code: currentCode,
        savedAt: new Date().toISOString(),
        theme: theme,
        mode: languageMode
      };

      localStorage.setItem(storageKey, JSON.stringify(saveData));
      
      // 更新状态记录
      lastSavedCode.value = currentCode;
      lastSavedLanguage.value = currentLang;
      
      // 保存全局设置，包括当前语言
      saveGlobalSettings();
    } catch (error) {
      console.error('保存代码失败:', error);
    }
  }
}

// 代码解析
function handleCodeChange() {
  const code = editor.getValue();
  currentCode.value = code;
  
  // 标记用户正在输入
  isUserTyping.value = true;
  
  // 如果用户修改了代码，隐藏AI补全，但不重新请求
  if (showAICompletion.value && aiCompletionWidget.value) {
    console.log('用户修改代码，清除AI补全，不重新请求');
    clearInlineAICompletion();
    showAICompletion.value = false;
    aiCompletion.value = '';
    return; // 不继续执行，避免重新请求AI补全
  }
  
  if (code !== lastSavedCode.value || selectedLanguage.value !== lastSavedLanguage.value) {
    setTimeout(autoSave, 1500);
  }
  parseCodeForCompletions(code);
  
  // 触发AI补全（防抖处理）- 只有在用户真正修改代码时才触发
  const hasSubmissions = submissions.value && submissions.value.length > 0;
  if (hasSubmissions && code.trim().length > 0 && isUserTyping.value) {
    console.log('用户修改代码，准备触发AI补全', {
      hasSubmissions: hasSubmissions,
      submissionsCount: submissions.value?.length || 0,
      codeLength: code.trim().length,
      isUserTyping: isUserTyping.value
    });
    requestAICompletion(); // 使用防抖函数
  }
  
  // 延迟重置用户输入标志
  setTimeout(() => {
    isUserTyping.value = false;
  }, 1000);
}

// 全屏切换函数 - 使用CSS布局控制，占满浏览器窗口
function toggleQuestionFullscreen() {
  isQuestionFullscreen.value = !isQuestionFullscreen.value;
  // 退出其他全屏状态
  if (isQuestionFullscreen.value) {
    isCodeFullscreen.value = false;
  }
}

function toggleCodeFullscreen() {
  isCodeFullscreen.value = !isCodeFullscreen.value;
  // 退出其他全屏状态
  if (isCodeFullscreen.value) {
    isQuestionFullscreen.value = false;
  }
}

// 加载提交记录
async function loadSubmissions() {
  if (!questionId.value) {
    return;
  }
  
  submissionsLoading.value = true;
  submissionsError.value = '';
  
  try {
    const params = {
      page: 1,
      page_size: 20,
      language: languageFilter.value !== 'all' ? languageFilter.value : undefined,
      status: statusFilter.value !== 'all' ? statusFilter.value : undefined,
    };
    
    const response = await submissionApi.getSubmissions(questionId.value, params);
    
    if (response && response.data) {
      submissions.value = response.data.submissions || [];
    } else {
      submissions.value = [];
    }
  } catch (error) {
    console.error('加载提交记录失败:', error);
    submissionsError.value = error.message || '加载提交记录失败';
    submissions.value = [];
  } finally {
    submissionsLoading.value = false;
  }
}

// 加载题解列表
async function loadSolutions() {
  if (!questionId.value) {
    return;
  }
  
  solutionsLoading.value = true;
  solutionsError.value = '';
  
  try {
    const params = {
      page: 1,
      page_size: 20,
    };
    
    const response = await solutionApi.getSolutions(questionId.value, params);
    
    if (response && response.data) {
      solutions.value = response.data.solutions || [];
    } else {
      solutions.value = [];
    }
  } catch (error) {
    console.error('加载题解失败:', error);
    solutionsError.value = error.message || '加载题解失败';
    solutions.value = [];
  } finally {
    solutionsLoading.value = false;
  }
}

// 查看提交记录详情
async function viewSubmissionDetail(submission) {
  try {
    // 如果是当前提交记录，直接使用缓存的数据
    if (currentSubmission.value && submission.id === currentSubmission.value.id) {
      selectedSubmission.value = currentSubmission.value;
      showSubmissionDetail.value = true;
    } else {
      // 否则从API获取详情
      const response = await submissionApi.getSubmissionDetail(submission.id);
      selectedSubmission.value = response.data;
      showSubmissionDetail.value = true;
    }
    
    // 获取排名信息
    await loadSubmissionRanking(selectedSubmission.value);
  } catch (error) {
    console.error('获取提交记录详情失败:', error);
    showToast('获取提交记录详情失败', 'error');
  }
}

// 加载提交记录排名信息
async function loadSubmissionRanking(submission) {
  try {
    const response = await submissionApi.getSubmissionRanking(submission.id);
    if (response.data) {
      selectedSubmission.value.timeRank = response.data.time_rank;
      selectedSubmission.value.memoryRank = response.data.memory_rank;
      
      // 确保有分布数据，如果没有则生成
      let timeDistribution = response.data.time_distribution;
      let memoryDistribution = response.data.memory_distribution;
      
      if (!timeDistribution || !Array.isArray(timeDistribution)) {
        timeDistribution = generateDistributionData(response.data.time_rank, response.data.total_count);
      }
      
      if (!memoryDistribution || !Array.isArray(memoryDistribution)) {
        memoryDistribution = generateDistributionData(response.data.memory_rank, response.data.total_count);
      }
      
      rankingStats.value = {
        time_rank: response.data.time_rank,
        memory_rank: response.data.memory_rank,
        total_count: response.data.total_count,
        time_distribution: timeDistribution,
        memory_distribution: memoryDistribution
      };
    } else {
      // 如果没有数据，设置一些测试数据
      rankingStats.value = {
        time_rank: 1,
        memory_rank: 2,
        total_count: 10,
        time_distribution: [1, 2, 3, 2, 2],
        memory_distribution: [2, 1, 3, 2, 2]
      };
    }
  } catch (error) {
    console.error('获取排名信息失败:', error);
    // 设置测试数据以便调试
    rankingStats.value = {
      time_rank: 1,
      memory_rank: 2,
      total_count: 10,
      time_distribution: [1, 2, 3, 2, 2],
      memory_distribution: [2, 1, 3, 2, 2]
    };
  }
}

// 生成分布数据的辅助函数
function generateDistributionData(rank, totalCount) {
  const distribution = [0, 0, 0, 0, 0]; // 5个区间
  
  if (totalCount <= 0) return distribution;
  
  // 计算当前排名在哪个区间
  const percentage = (rank / totalCount) * 100;
  let rangeIndex = 0;
  
  if (percentage <= 10) rangeIndex = 0;
  else if (percentage <= 25) rangeIndex = 1;
  else if (percentage <= 50) rangeIndex = 2;
  else if (percentage <= 75) rangeIndex = 3;
  else rangeIndex = 4;
  
  // 在当前区间设置一个值，其他区间随机分布
  distribution[rangeIndex] = 1;
  
  // 为其他区间生成一些随机数据
  for (let i = 0; i < 5; i++) {
    if (i !== rangeIndex) {
      distribution[i] = Math.floor(Math.random() * 3) + 1;
    }
  }
  
  return distribution;
}

// 关闭提交记录详情
function closeSubmissionDetail() {
  showSubmissionDetail.value = false;
  selectedSubmission.value = null;
}

// 复制代码到剪贴板
async function copyCode() {
  if (!selectedSubmission.value?.code) return;
  
  try {
    await navigator.clipboard.writeText(selectedSubmission.value.code);
  } catch (error) {
    console.error('复制失败:', error);
  }
}

// 复制代码到编辑区
function copyToEditor() {
  if (!selectedSubmission.value?.code) return;
  
  // 设置语言
  selectedLanguage.value = selectedSubmission.value.language;
  
  // 等待语言切换完成后再设置代码
  nextTick(() => {
    if (editor) {
      // 设置代码到编辑器
      editor.setValue(selectedSubmission.value.code);
      // 更新当前代码状态
      currentCode.value = selectedSubmission.value.code;
      // 保存到本地存储
      const storageKey = getStorageKey();
      localStorage.setItem(storageKey, JSON.stringify({
        code: selectedSubmission.value.code,
        language: selectedSubmission.value.language,
        timestamp: Date.now()
      }));
    }
  });
  
  // 切换到代码编辑标签页
  activeTab.value = 'detail';
}

// 获取排名区间标签
function getRankRange(index) {
  const ranges = [
    '1-10%',
    '11-25%',
    '26-50%',
    '51-75%',
    '76-100%'
  ];
  return ranges[index] || `${index * 20 + 1}-${(index + 1) * 20}%`;
}

// 判断排名是否在指定区间内
function isInRankRange(rank, rangeIndex) {
  if (!rankingStats.value?.total_count) return false;
  
  const totalCount = rankingStats.value.total_count;
  const percentage = (rank / totalCount) * 100;
  
  const ranges = [
    { min: 0, max: 10 },
    { min: 10, max: 25 },
    { min: 25, max: 50 },
    { min: 50, max: 75 },
    { min: 75, max: 100 }
  ];
  
  const range = ranges[rangeIndex];
  return range && percentage > range.min && percentage <= range.max;
}

// 查看题解详情
async function viewSolutionDetail(solution) {
  try {
    const response = await solutionApi.getSolutionDetail(solution.id);
    selectedSolution.value = response.data;
    showSolutionDetail.value = true;
  } catch (error) {
    console.error('获取题解详情失败:', error);
  }
}

// 关闭题解详情
function closeSolutionDetail() {
  showSolutionDetail.value = false;
  selectedSolution.value = null;
}

// 加载讨论区列表
async function loadDiscussions() {
  if (!questionId.value) {
    return;
  }
  
  discussionsLoading.value = true;
  discussionsError.value = '';
  
  try {
    const params = {
      page: 1,
      page_size: 20,
      category: 'question'
    };
    
    const response = await discussionApi.getDiscussions(params);
    
    if (response && response.data) {
      discussions.value = response.data.discussions || [];
    } else {
      discussions.value = [];
    }
  } catch (error) {
    console.error('加载讨论区失败:', error);
    discussionsError.value = error.message || '加载讨论区失败';
    discussions.value = [];
  } finally {
    discussionsLoading.value = false;
  }
}

// 查看讨论详情
async function viewDiscussionDetail(discussion) {
  try {
    const response = await discussionApi.getDiscussionDetail(discussion.id);
    // 这里可以打开讨论详情模态框或跳转到详情页面
    console.log('查看讨论详情:', response.data);
  } catch (error) {
    console.error('获取讨论详情失败:', error);
  }
}

// 获取状态样式类
function getStatusClass(status) {
  switch (status) {
    case 'accepted':
      return 'bg-green-100 text-green-800';
    case 'wrong_answer':
      return 'bg-red-100 text-red-800';
    case 'time_limit_exceeded':
      return 'bg-yellow-100 text-yellow-800';
    case 'memory_limit_exceeded':
      return 'bg-orange-100 text-orange-800';
    case 'runtime_error':
      return 'bg-purple-100 text-purple-800';
    case 'compile_error':
      return 'bg-gray-100 text-gray-800';
    case 'pending':
    case 'judging':
      return 'bg-blue-100 text-blue-800';
    default:
      return 'bg-gray-100 text-gray-800';
  }
}

// 获取状态图标样式类
function getStatusIconClass(status) {
  switch (status) {
    case 'accepted':
      return 'bg-gradient-to-br from-green-400 to-green-600 text-white';
    case 'wrong_answer':
      return 'bg-gradient-to-br from-red-400 to-red-600 text-white';
    case 'time_limit_exceeded':
      return 'bg-gradient-to-br from-yellow-400 to-yellow-600 text-white';
    case 'memory_limit_exceeded':
      return 'bg-gradient-to-br from-orange-400 to-orange-600 text-white';
    case 'runtime_error':
      return 'bg-gradient-to-br from-purple-400 to-purple-600 text-white';
    case 'compile_error':
      return 'bg-gradient-to-br from-gray-400 to-gray-600 text-white';
    case 'pending':
    case 'judging':
      return 'bg-gradient-to-br from-blue-400 to-blue-600 text-white';
    default:
      return 'bg-gradient-to-br from-gray-400 to-gray-600 text-white';
  }
}

// 获取状态名称
function getStatusName(status) {
  switch (status) {
    case 'accepted':
      return '通过';
    case 'wrong_answer':
      return '答案错误';
    case 'time_limit_exceeded':
      return '超时';
    case 'memory_limit_exceeded':
      return '内存超限';
    case 'runtime_error':
      return '运行时错误';
    case 'compile_error':
      return '编译错误';
    case 'pending':
      return '等待中';
    case 'judging':
      return '评测中';
    default:
      return '未知';
  }
}

// 获取语言名称
function getLanguageName(language) {
  switch (language) {
    case 'python':
      return 'Python';
    case 'java':
      return 'Java';
    case 'cpp':
      return 'C++';
    case 'c':
      return 'C';
    case 'javascript':
      return 'JavaScript';
    case 'go':
      return 'Go';
    case 'rust':
      return 'Rust';
    default:
      return language;
  }
}

// 格式化时间
function formatTime(timeStr) {
  const date = new Date(timeStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;
  
  return date.toLocaleDateString();
}


// 解析代码提取补全项 - 只提取当前代码中的字段和单词
function parseCodeForCompletions(code) {
  const completions = [];

  // 按语言解析自定义元素
  switch (selectedLanguage.value) {
    case 'python':
      completions.push(...parsePythonCode(code));
      break;
    case 'java':
      completions.push(...parseJavaCode(code));
      break;
    case 'cpp':
      completions.push(...parseCppCode(code));
      break;
  }

  // 提取所有单词（变量名、函数名等）
  completions.push(...extractAllWords(code));

  // 去重
  const uniqueCompletions = Array.from(new Map(
    completions.map(item => [item.text, item])
  ).values());

  customCompletions.value = uniqueCompletions;
}

// 提取代码中的所有单词
function extractAllWords(code) {
  const completions = [];
  
  // 匹配所有标识符（变量名、函数名、类名等）
  const wordRegex = /\b[a-zA-Z_][a-zA-Z0-9_]*\b/g;
  let match;
  
  while ((match = wordRegex.exec(code))) {
    const word = match[0];
    // 过滤掉太短的单词和纯数字
    if (word.length >= 2 && !/^\d+$/.test(word)) {
      completions.push({
        text: word,
        displayText: word,
        type: 'variable'
      });
    }
  }
  
  return completions;
}

// Python代码解析
function parsePythonCode(code) {
  const completions = [];

  // 匹配函数定义
  const funcRegex = /(?:@\w+\s*\n\s*)?def\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/g;
  let match;
  while ((match = funcRegex.exec(code))) {
    completions.push({
      text: match[1] + '()',
      displayText: match[1] + '()',
      type: 'function'
    });
  }

  // 匹配类定义
  const classRegex = /class\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*[:(]/g;
  while ((match = classRegex.exec(code))) {
    completions.push({
      text: match[1],
      displayText: match[1],
      type: 'class'
    });
  }

  // 匹配变量定义
  const varRegex = /^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=.*(?![:{])/gm;
  while ((match = varRegex.exec(code))) {
    completions.push({
      text: match[1],
      displayText: match[1],
      type: 'variable'
    });
  }

  return completions;
}

// Java代码解析
function parseJavaCode(code) {
  const completions = [];
  const funcRegex = /(public|private|protected|static)\s+\w+\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/g;
  const classRegex = /class\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\{/g;
  const varRegex = /(public|private|protected|static)\s+\w+\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*[=;]/g;

  let match;
  while ((match = funcRegex.exec(code))) {
    completions.push({ 
      text: match[2] + '()', 
      displayText: match[2] + '()', 
      type: 'method' 
    });
  }
  while ((match = classRegex.exec(code))) {
    completions.push({ 
      text: match[1], 
      displayText: match[1], 
      type: 'class' 
    });
  }
  while ((match = varRegex.exec(code))) {
    completions.push({ 
      text: match[2], 
      displayText: match[2], 
      type: 'variable' 
    });
  }

  return completions;
}

function parseCppCode(code) {
  const completions = [];
  
  // 第一步：先移除所有注释（单行// 和 多行/* */），避免解析注释中的内容
  const codeWithoutComments = code
    .replace(/\/\/.*$/gm, '')          // 移除单行注释（// 到行尾）
    .replace(/\/\*[\s\S]*?\*\//g, '');// 移除多行注释（/* 到 */，非贪婪匹配）

  // 第二步：定义正则表达式（重点新增模板相关匹配规则）
  const regexRules = [
    // 1. 模板类/结构体声明（如：template <typename T> class MyClass / struct MyStruct）
    {
      regex: /template\s*<[^>]+>\s*(class|struct)\s+([a-zA-Z_][a-zA-Z0-9_]*)/g,
      handler: (match) => {
        const type = match[1]; // "class" 或 "struct"
        const name = match[2]; // 模板类/结构体名（如MyClass）
        completions.push({
          text: name,
          displayText: `${name} (模板${type})`,
          type: type // 标记为"class"或"struct"类型
        });
      }
    },

    // 2. 模板类实例化/使用时的类名（如：MyClass<int> obj / vector<string> list）
    {
      regex: /([a-zA-Z_][a-zA-Z0-9_]*)\s*</g,
      handler: (match) => {
        const name = match[1]; // <前的类名（如MyClass、vector）
        // 避免重复添加（比如模板类声明已添加过，实例化时不再重复）
        const isDuplicate = completions.some(item => 
          item.text === name && (item.type === 'class' || item.type === 'struct' || item.type === 'template-class')
        );
        if (!isDuplicate) {
          completions.push({
            text: name,
            displayText: `${name} (模板类)`,
            type: 'template-class' // 专门标记模板类实例化场景
          });
        }
      }
    },

    // 3. 模板函数声明（如：template <typename T> MyClass<T> getObj()）
    {
      regex: /template\s*<[^>]+>\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*<[^>]+>\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/g,
      handler: (match) => {
        const returnTypeClass = match[1]; // 返回值的类名（如MyClass）
        const funcName = match[2];       // 函数名（如getObj）
        
        // 添加返回值的类名（<前的类名）
        const isReturnTypeDuplicate = completions.some(item => 
          item.text === returnTypeClass && (item.type === 'class' || item.type === 'template-class')
        );
        if (!isReturnTypeDuplicate) {
          completions.push({
            text: returnTypeClass,
            displayText: `${returnTypeClass} (模板类)`,
            type: 'template-class'
          });
        }

        // 添加模板函数名（带()）
        completions.push({
          text: funcName + '()',
          displayText: `${funcName}() (模板函数)`,
          type: 'function'
        });
      }
    },

    // 4. 普通类/结构体声明（非模板，如：class Person / struct Point）
    {
      regex: /(class|struct)\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\{/g,
      handler: (match) => {
        const type = match[1];
        const name = match[2];
        completions.push({
          text: name,
          displayText: `${name} (${type})`,
          type: type
        });
      }
    },

    // 5. 普通函数声明（含返回值是模板类的情况，如：vector<int> getNums()）
    {
      regex: /([a-zA-Z_][a-zA-Z0-9_]*)(\s*<[^>]+>)?\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/g,
      handler: (match) => {
        const returnType = match[1]; // 返回值类名（如vector）
        const funcName = match[3];   // 函数名（如getNums）
        
        // 添加返回值的类名（可能是模板类，如vector）
        const isReturnTypeDuplicate = completions.some(item => 
          item.text === returnType && (item.type === 'class' || item.type === 'template-class')
        );
        if (!isReturnTypeDuplicate) {
          completions.push({
            text: returnType,
            displayText: `${returnType} (类/模板类)`,
            type: 'template-class' // 统一标记为模板类（兼容普通类）
          });
        }

        // 添加函数名（带()）
        completions.push({
          text: funcName + '()',
          displayText: `${funcName}()`,
          type: 'function'
        });
      }
    },

    // 6. 变量声明（含模板类变量，如：MyClass<int> obj / int age）
    {
      regex: /([a-zA-Z_][a-zA-Z0-9_]*)(\s*<[^>]+>)?\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*[=;]/g,
      handler: (match) => {
        const varType = match[1];  // 变量类型（如MyClass、int）
        const varName = match[3];  // 变量名（如obj、age）
        
        // 添加变量类型的类名（如MyClass，可能是模板类）
        if (varType.match(/^[A-Z]/)) { // 类名通常首字母大写，过滤基本类型（如int、bool）
          const isTypeDuplicate = completions.some(item => 
            item.text === varType && (item.type === 'class' || item.type === 'template-class')
          );
          if (!isTypeDuplicate) {
            completions.push({
              text: varType,
              displayText: `${varType} (类/模板类)`,
              type: 'template-class'
            });
          }
        }

        // 添加变量名
        completions.push({
          text: varName,
          displayText: `${varName} (变量)`,
          type: 'variable'
        });
      }
    },

    // 7. 枚举声明（如：enum Color / enum class Direction）
    {
      regex: /enum\s+(class)?\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\{/g,
      handler: (match) => {
        const isScoped = match[1] ? ' (强类型)' : ''; // 是否为enum class
        const name = match[2];
        completions.push({
          text: name,
          displayText: `${name} (枚举${isScoped})`,
          type: 'enum'
        });
      }
    },

    // 8. 命名空间声明（如：namespace MySpace）
    {
      regex: /namespace\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\{/g,
      handler: (match) => {
        const name = match[1];
        completions.push({
          text: name,
          displayText: `${name} (命名空间)`,
          type: 'namespace'
        });
      }
    }
  ];

  // 第三步：执行所有正则匹配和处理
  regexRules.forEach(rule => {
    let match;
    // 循环匹配所有符合规则的内容
    while ((match = rule.regex.exec(codeWithoutComments)) !== null) {
      rule.handler(match);
    }
  });

  // 第四步：去重（避免同一标识符被多次添加，如模板类声明和实例化都匹配到）
  const uniqueCompletions = Array.from(
    new Map(completions.map(item => [item.text, item])).values()
  );

  return uniqueCompletions;
}

// 补全配置
function configureAutocomplete() {
  if (!editor) return;

  // 1. 注册自定义补全器
  CodeMirror.registerHelper('hint', 'custom', function(cm) {
    const cursor = cm.getCursor();
    const token = cm.getTokenAt(cursor);
    const currentWord = token.string;
    
    // 计算补全范围
    const start = { line: cursor.line, ch: token.start };
    const end = { line: cursor.line, ch: token.end };
    
    // 过滤匹配的补全项
    const filtered = customCompletions.value.filter(item => 
      item.text.toLowerCase().startsWith(currentWord.toLowerCase())
    );
    
    return {
      list: filtered,
      from: start,
      to: end
    };
  });

  // 2. 补全触发函数
  function triggerCompletion() {
    // 关闭任何已存在的补全菜单
    if (editor.state.completionActive) {
      editor.state.completionActive.close();
    }
    
    // 触发补全
    CodeMirror.showHint(editor, CodeMirror.hint.custom, {
      completeSingle: false
    });
  }

  // 3. 输入时自动触发补全和AI补全
  editor.on('inputRead', function() {
    const cursor = editor.getCursor();
    const token = editor.getTokenAt(cursor);
    
    // 触发字符列表
    const triggerChars = ['.', ' ', '(', '[', '{', '=', ','];
    
    // 当输入触发字符或关键字/变量时显示补全
    if (triggerChars.includes(token.string) || 
        (token.type && (token.type.includes('keyword') || 
                       token.type.includes('variable') ||
                       token.type.includes('atom')))) {
      setTimeout(triggerCompletion, 100);
    }
    
    // 触发AI补全（延迟执行，避免频繁请求）
    if (hasSubmitted.value) {
      setTimeout(() => {
        requestAICompletion();
      }, 1000); // 1秒延迟，避免用户还在输入时频繁请求
    }
  });

  // 4. 设置快捷键
  editor.setOption('extraKeys', {
    // Ctrl+空格手动触发补全
    'Ctrl-Space': triggerCompletion,
    
    // Tab键补全
    'Tab': function(cm) {
      console.log('Tab键被按下', {
        showAICompletion: showAICompletion.value,
        aiCompletion: aiCompletion.value,
        aiCompletionWidget: aiCompletionWidget.value
      });
      
      // 优先处理AI补全
      if (showAICompletion.value && aiCompletion.value && aiCompletionWidget.value) {
        console.log('Tab键接受AI补全');
        applyAICompletion();
        return true;
      }
      
      // 处理普通补全
      if (cm.state.completionActive) {
        cm.state.completionActive.pick();
        return true;
      }
      
      // 没有补全时插入4个空格（而不是制表符）
      cm.replaceSelection('    ', 'end');
      return true;
    },
    
    // Enter键处理 - 增强的自动缩进和格式化
    'Enter': function(cm) {
      if (cm.state.completionActive) {
        cm.state.completionActive.pick();
        // 补全后换行
        setTimeout(() => {
          handleEnterKey(cm);
        }, 10);
        return true;
      }
      // 正常换行
      handleEnterKey(cm);
      return true;
    },
    
    // 格式化当前行
    'Ctrl-L': function(cm) {
      const cursor = cm.getCursor();
      const line = cm.getLine(cursor.line);
      const formatted = formatCurrentLine(line);
      if (formatted !== line) {
        cm.replaceRange(formatted, {line: cursor.line, ch: 0}, {line: cursor.line, ch: line.length});
      }
      return true;
    },
    
    // 格式化整个文档
    'Ctrl-Shift-L': function(cm) {
      const totalLines = cm.lineCount();
      for (let i = 0; i < totalLines; i++) {
        const line = cm.getLine(i);
        const formatted = formatCurrentLine(line);
        if (formatted !== line) {
          cm.replaceRange(formatted, {line: i, ch: 0}, {line: i, ch: line.length});
        }
      }
      return true;
    },
    
    // 删除当前行
    'Ctrl-D': function(cm) {
      const cursor = cm.getCursor();
      cm.replaceRange('', {line: cursor.line, ch: 0}, {line: cursor.line + 1, ch: 0});
      return true;
    },
    
    // Escape键取消AI补全
    'Esc': function(cm) {
      if (showAICompletion.value && aiCompletionWidget.value) {
        console.log('Escape键取消AI补全');
        cancelAICompletion();
        return true;
      }
      return false;
    },
    
    // 复制当前行
    'Ctrl-Shift-D': function(cm) {
      const cursor = cm.getCursor();
      const line = cm.getLine(cursor.line);
      cm.replaceRange(line + '\n', {line: cursor.line, ch: 0}, {line: cursor.line, ch: 0});
      return true;
    }
  });
}

// 处理Enter键 - 智能缩进和格式化
function handleEnterKey(cm) {
  const cursor = cm.getCursor();
  const line = cm.getLine(cursor.line);
  const beforeCursor = line.substring(0, cursor.ch);
  const afterCursor = line.substring(cursor.ch);
  
  // 格式化上一行代码（如果有未闭合的括号、引号等）
  formatPreviousLine(cm, cursor.line);
  
  // 计算新行的缩进
  let newIndent = calculateIndent(line, beforeCursor, afterCursor);
  
  // 插入换行和缩进
  cm.replaceSelection('\n' + newIndent, 'end');
  
  // 如果新行需要额外缩进（如函数体、循环体等）
  if (needsExtraIndent(beforeCursor)) {
    cm.replaceSelection('\t', 'end');
  }
}

// 格式化上一行代码
function formatPreviousLine(cm, lineNum) {
  if (lineNum <= 0) return;
  
  const prevLine = cm.getLine(lineNum - 1);
  const trimmed = prevLine.trim();
  
  // 如果上一行有未闭合的括号，添加适当的空格
  if (trimmed.includes('{') && !trimmed.includes('}')) {
    // 在 { 后添加空格（如果还没有）
    if (trimmed.includes('{') && !trimmed.includes('{ ')) {
      const newLine = prevLine.replace('{', '{ ');
      cm.replaceRange(newLine, {line: lineNum - 1, ch: 0}, {line: lineNum - 1, ch: prevLine.length});
    }
  }
  
  // 如果上一行有函数定义，确保格式正确
  if (trimmed.includes('def ') || trimmed.includes('function ') || trimmed.includes('()')) {
    // 确保函数名和括号之间有空格
    const formatted = prevLine.replace(/(\w+)\s*\(/g, '$1 (');
    if (formatted !== prevLine) {
      cm.replaceRange(formatted, {line: lineNum - 1, ch: 0}, {line: lineNum - 1, ch: prevLine.length});
    }
  }
}

// 计算新行的缩进
function calculateIndent(line, beforeCursor, afterCursor) {
  // 获取当前行的缩进
  const currentIndent = line.match(/^\s*/)[0];
  
  // 如果当前行有未闭合的括号，保持相同缩进
  if (beforeCursor.includes('{') && !beforeCursor.includes('}')) {
    return currentIndent;
  }
  
  // 如果当前行以冒号结尾（Python），增加缩进
  if (beforeCursor.trim().endsWith(':')) {
    return currentIndent + '\t';
  }
  
  // 如果当前行是函数定义、类定义等，增加缩进
  if (beforeCursor.trim().match(/(def|class|if|for|while|try|with)\s+\w+/)) {
    return currentIndent + '\t';
  }
  
  // 默认保持相同缩进
  return currentIndent;
}

// 判断是否需要额外缩进
function needsExtraIndent(beforeCursor) {
  const trimmed = beforeCursor.trim();
  
  // 如果以这些关键字结尾，需要额外缩进
  const indentKeywords = ['def', 'class', 'if', 'for', 'while', 'try', 'with', 'else', 'elif', 'except', 'finally'];
  
  for (const keyword of indentKeywords) {
    if (trimmed.endsWith(keyword) || trimmed.endsWith(keyword + ':')) {
      return true;
    }
  }
  
  // 如果以冒号结尾，需要额外缩进
  if (trimmed.endsWith(':')) {
    return true;
  }
  
  return false;
}

// 格式化当前行代码
function formatCurrentLine(line) {
  let formatted = line;
  
  // 移除多余的空格
  formatted = formatted.replace(/\s+/g, ' ').trim();
  
  // 在操作符周围添加空格
  formatted = formatted.replace(/([+\-*/=<>!&|])(?!=)/g, ' $1 ');
  formatted = formatted.replace(/\s+/g, ' ');
  
  // 在逗号后添加空格
  formatted = formatted.replace(/,/g, ', ');
  
  // 在冒号后添加空格（如果不是在字典或切片中）
  formatted = formatted.replace(/:(?!\s)/g, ': ');
  
  // 在括号内移除多余空格
  formatted = formatted.replace(/\(\s+/g, '(');
  formatted = formatted.replace(/\s+\)/g, ')');
  formatted = formatted.replace(/\[\s+/g, '[');
  formatted = formatted.replace(/\s+\]/g, ']');
  formatted = formatted.replace(/\{\s+/g, '{');
  formatted = formatted.replace(/\s+\}/g, '}');
  
  // 移除多余的空格
  formatted = formatted.replace(/\s+/g, ' ').trim();
  
  return formatted;
}

// 组件挂载（初始化编辑器）
onMounted(async () => {
  // 加载题目数据
  await loadQuestion();
  
  // 加载题目列表（用于侧边栏）
  await loadQuestionList();
  
  // 预加载其他数据，提升用户体验
  loadSubmissions();
  loadSolutions();
  loadDiscussions();
  
  // 加载代码补全设置
  const savedCodeCompletionSetting = localStorage.getItem('codeCompletionDisabled');
  if (savedCodeCompletionSetting !== null) {
    isCodeCompletionDisabled.value = savedCodeCompletionSetting === 'true';
  }
  
  if (editorContainer.value) {
    // 新增：加载全局设置，获取上次使用的语言
    const globalSettings = loadGlobalSettings();
    let initialLang = 'cpp'; // 默认值
    
    // 如果有保存的语言设置，则使用保存的语言
    if (globalSettings && globalSettings.lastUsedLanguage) {
      initialLang = globalSettings.lastUsedLanguage;
      selectedLanguage.value = initialLang;
    }
    
    lastSavedLanguage.value = initialLang; // 初始化上次保存的语言
    
    // 加载当前题目+当前语言的历史数据
    const savedData = loadSavedCode();
    const savedCode = savedData ? savedData.code : null;
    const savedTheme = savedData ? savedData.theme : null;
    const savedMode = savedData ? savedData.mode : null;

    // 如果有保存的主题设置，则使用保存的主题
    if (globalSettings && globalSettings.lastUsedTheme) {
      selectedTheme.value = globalSettings.lastUsedTheme;
    }

    // 初始化CodeMirror编辑器
    editor = CodeMirror(editorContainer.value, {
      mode: savedMode || (initialLang === 'python' ? 'python' : initialLang === 'java' ? 'text/x-java' : 'text/x-c++src'),
      theme: savedTheme || selectedTheme.value,
      lineNumbers: true,
      autoCloseBrackets: true,
      autoCloseTags: true,
      matchBrackets: true,
      indentUnit: 4,
      indentWithTabs: false,
      smartIndent: true,
      electricChars: true,
      lineWrapping: false,
      foldGutter: true,
      gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
      value: savedCode || getInitialCodeForLanguage(initialLang),
      extraKeys: {} // 初始为空，后面会被配置
    });

    // 初始化补全功能
    configureAutocomplete();
    // 初始解析代码生成补全项
    if (savedCode) {
      parseCodeForCompletions(savedCode);
    } else {
      parseCodeForCompletions(editor.getValue());
    }

    // 绑定代码变化监听和自动保存
    lastSavedCode.value = editor.getValue();
    autoSaveInterval.value = setInterval(autoSave, 3000);
    editor.on('change', debounce(handleCodeChange, 300));
  }
});

// 防抖函数
function debounce(func, delay) {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), delay);
  };
}

// 主题和语言切换
const changeTheme = () => {
  if (editor) {
    const currentThemeClass = editor.getWrapperElement().className
      .split(' ')
      .find(cls => cls.startsWith('cm-s-'));
    if (currentThemeClass) {
      editor.getWrapperElement().classList.remove(currentThemeClass);
    }
    editor.setOption('theme', selectedTheme.value);
    runOutput.value = `已切换到 ${selectedTheme.value} 主题`;
    
    // 切换主题后保存全局设置
    saveGlobalSettings();
  }
};

// 语言切换逻辑
const changeLanguage = () => {
  if (!editor) return;
  
  // 切换前先保存当前语言的代码
  const currentCode = editor.getValue();
  if (currentCode !== lastSavedCode.value) {
    autoSave(); // 立即保存当前语言的代码
  }

  // 根据目标语言设置编辑器配置并加载历史代码
  const targetLang = selectedLanguage.value;
  let defaultCode = '';
  let mode = '';

  // 获取BaseCode或设置默认代码
  const basecode = currentQuestion.value?.basecode || {};
  if (basecode[targetLang]) {
    // 使用API返回的BaseCode
    defaultCode = basecode[targetLang];
  } else {
    // 设置默认代码或显示不支持信息
    defaultCode = `// 暂不支持${targetLang}语言\n// 请选择其他语言或联系管理员添加支持`;
  }
  
  // 设置各语言的语法模式
  switch (targetLang) {
    case 'python':
      mode = 'python';
      break;
    case 'java':
      mode = 'text/x-java';
      break;
    case 'cpp':
      mode = 'text/x-c++src';
      break;
    case 'c':
      mode = 'text/x-csrc';
      break;
    case 'javascript':
      mode = 'javascript';
      break;
    case 'go':
      mode = 'go';
      break;
    case 'rust':
      mode = 'rust';
      break;
    default:
      mode = 'text/plain';
  }

  // 更新编辑器配置
  editor.setOption('mode', mode);
  
  // 加载目标语言的历史代码（无历史则用默认代码）
  const savedData = loadSavedCode();
  const codeToLoad = savedData ? savedData.code : defaultCode;
  
  // 更新编辑器内容和状态
  editor.setValue(codeToLoad);
  lastSavedCode.value = codeToLoad;
  lastSavedLanguage.value = targetLang; // 同步上次保存的语言

  // 重新生成当前语言的补全项
  customCompletions.value = [];
  parseCodeForCompletions(codeToLoad);
  
  // 提示用户语言切换完成
  runOutput.value = `已切换到 ${targetLang} 语言，加载${savedData ? '历史' : '默认'}代码`;
  
  // 切换语言后保存全局设置
  saveGlobalSettings();
};

const categories = ref([
  { id: 1, name: "热门推荐", icon: "fa-star", count: "0", badgeClass: "bg-gray-200 text-gray-700 text-xs px-2 py-0.5 rounded-full" },
  { id: 2, name: "简单", icon: "fa-signal", count: "0", badgeClass: "bg-green-100 text-green-800 text-xs px-2 py-0.5 rounded-full" },
  { id: 3, name: "中等", icon: "fa-balance-scale", count: "0", badgeClass: "bg-yellow-100 text-yellow-800 text-xs px-2 py-0.5 rounded-full" },
  { id: 4, name: "困难", icon: "fa-fire", count: "0", badgeClass: "bg-red-100 text-red-800 text-xs px-2 py-0.5 rounded-full" }
]);


// 题目列表（用于侧边栏显示）
const questionList = ref([]);
const questionListLoading = ref(false);
const questionListError = ref('');

// 当前题目在侧边栏列表中的序号（用于显示编号）
const currentQuestionNumber = computed(() => {
  const q = currentQuestion.value;
  if (!q) return '';
  const idx = questionList.value.findIndex(item => item.id === q.id);
  return idx >= 0 ? idx + 1 : q.id;
});

// 辅助方法
const toggleSidebar = () => {
  sidebarExpanded.value = !sidebarExpanded.value;
  showSaveToast.value = true;
  setTimeout(() => showSaveToast.value = false, 2000);
};

// 加载题目列表
const loadQuestionList = async () => {
  try {
    questionListLoading.value = true;
    questionListError.value = '';
    
    const success = await questionStore.fetchQuestions({
      page: 1,
      page_size: 50, // 获取更多题目用于侧边栏显示
      difficulty: [],
      tags: [],
      status: [],
      search: ''
    });
    
    if (success && questionStore.questions) {
      // 格式化题目数据以适配模板
      questionList.value = questionStore.questions.map(question => ({
        id: question.id,
        title: question.title,
        difficulty: question.difficulty,
        difficultyText: getDifficultyText(question.difficulty),
        difficultyBadgeClass: getDifficultyBadgeClass(question.difficulty),
        submission_count: question.submission_count || 0,
        solution_count: question.solution_count || 0,
        acceptance_rate: question.acceptance_rate || 0
      }));
    }
    
    // 加载题目统计数据
    await loadQuestionStats();
  } catch (error) {
    console.error('加载题目列表失败:', error);
    questionListError.value = '加载题目列表失败';
  } finally {
    questionListLoading.value = false;
  }
};

// 加载题目统计数据
const loadQuestionStats = async () => {
  try {
    const response = await questionApi.getGlobalQuestionStats();
    if (response.data) {
      // 更新分类统计数据
      categories.value[1].count = response.data.difficulty_stats.easy.toString(); // 简单
      categories.value[2].count = response.data.difficulty_stats.medium.toString(); // 中等
      categories.value[3].count = response.data.difficulty_stats.hard.toString(); // 困难
      categories.value[0].count = response.data.popular_questions.toString(); // 热门推荐
    }
  } catch (error) {
    console.error('加载题目统计数据失败:', error);
  }
};

// 获取难度文本
const getDifficultyText = (difficulty) => {
  const difficultyMap = {
    'Easy': '简单',
    'Medium': '中等', 
    'Hard': '困难'
  };
  return difficultyMap[difficulty] || difficulty;
};

// 获取难度样式类
const getDifficultyBadgeClass = (difficulty) => {
  const classMap = {
    'Easy': 'bg-green-100 text-green-800',
    'Medium': 'bg-yellow-100 text-yellow-800',
    'Hard': 'bg-red-100 text-red-800'
  };
  return classMap[difficulty] || 'bg-gray-100 text-gray-800';
};

// 获取指定语言的初始代码
const getInitialCodeForLanguage = (language) => {
  if (!currentQuestion.value) {
    return `// 暂不支持${language}语言\n// 请选择其他语言或联系管理员添加支持`;
  }
  
  const basecode = currentQuestion.value.basecode || {};
  if (basecode[language]) {
    return basecode[language];
  } else {
    return `// 暂不支持${language}语言\n// 请选择其他语言或联系管理员添加支持`;
  }
};

// 初始化代码编辑器
const initializeCodeEditor = () => {
  if (!currentQuestion.value) return;
  
  // 获取当前语言的初始代码
  const currentLang = selectedLanguage.value;
  const initialCode = getInitialCodeForLanguage(currentLang);
  
  // 设置编辑器内容
  if (editor) {
    editor.setValue(initialCode);
    currentCode.value = initialCode;
  } else {
    // 如果编辑器还没初始化，先设置默认代码
    currentCode.value = initialCode;
  }
};

// 选择题目方法
const selectQuestion = (question) => {
  // 跳转到选中的题目
  window.location.href = `/questions/${question.id}`;
};

// AI相关方法
const handleAIToggle = () => {
  showAIChat.value = !showAIChat.value;
};

const handleAIWidthChange = (width) => {
  aiPanelWidth.value = width;
};

// 重置代码到初始模板
const resetCode = () => {
  if (!editor) return;
  const lang = selectedLanguage.value;
  const initialCode = getInitialCodeForLanguage(lang);
  // 设置编辑器内容与状态
  editor.setValue(initialCode);
  currentCode.value = initialCode;
  lastSavedCode.value = initialCode;
  lastSavedLanguage.value = lang;
  // 覆盖本地存储为初始模板，避免后续切换又加载旧代码
  try {
    const storageKey = getStorageKey();
    const saveData = {
      questionId: questionId.value,
      language: lang,
      code: initialCode,
      savedAt: new Date().toISOString(),
      theme: editor.getOption('theme'),
      mode: editor.getOption('mode')
    };
    localStorage.setItem(storageKey, JSON.stringify(saveData));
  } catch (e) {
    console.error('重置代码时保存到本地失败:', e);
  }
  // 清除输出与AI补全状态提示
  runOutput.value = '代码已重置为初始模板';
  runError.value = '';
  if (showAICompletion.value) {
    clearInlineAICompletion();
    showAICompletion.value = false;
    aiCompletion.value = '';
  }
};

// 请求AI代码补全（带防抖）
const requestAICompletion = () => {
  const hasSubmissions = submissions.value && submissions.value.length > 0;
  console.log('requestAICompletion 被调用', {
    hasSubmissions: hasSubmissions,
    submissionsCount: submissions.value?.length || 0,
    codeLength: currentCode.value.trim().length,
    isLoading: aiCompletionLoading.value,
    lastRequest: lastCompletionRequest.value === currentCode.value
  });
  
  if (!hasSubmissions || !currentCode.value.trim() || aiCompletionLoading.value || isSubmitting.value || !isUserTyping.value || isCodeCompletionDisabled.value) {
    console.log('AI补全条件不满足，退出', {
      hasSubmissions,
      hasCode: !!currentCode.value.trim(),
      isLoading: aiCompletionLoading.value,
      isSubmitting: isSubmitting.value,
      isUserTyping: isUserTyping.value,
      isDisabled: isCodeCompletionDisabled.value
    });
    return;
  }
  
  // 避免重复请求相同的代码
  if (lastCompletionRequest.value === currentCode.value) {
    console.log('代码未变化，跳过AI补全请求');
    return;
  }
  
  // 清除之前的定时器
  if (aiCompletionTimeout.value) {
    clearTimeout(aiCompletionTimeout.value);
  }
  
  // 设置防抖定时器，1秒后发送请求
  aiCompletionTimeout.value = setTimeout(async () => {
    await performAICompletion();
  }, 1000);
};

// 执行AI补全请求
const performAICompletion = async () => {
  console.log('开始请求AI代码补全...');
  aiCompletionLoading.value = true;
  lastCompletionRequest.value = currentCode.value;
  lastCompletionTime.value = Date.now();
  
  try {
    const response = await aiApi.codeCompletion({
      code: currentCode.value,
      language: selectedLanguage.value,
      question_id: questionId.value,
      current_position: getCurrentLineContent()
    });
    
    console.log('AI补全API响应:', response);
    
    if (response.data?.completion) {
      // 获取补全内容（后端已处理）
      let completionText = response.data.completion;
      
      // 如果补全内容为空，不显示
      if (!completionText) {
        console.log('AI补全内容为空，跳过显示');
        return;
      }
      
      aiCompletion.value = completionText;
      showAICompletion.value = true;
      console.log('AI补全成功，显示建议:', completionText);
      
      // 使用nextTick确保DOM更新后再显示补全
      await nextTick();
      // 在编辑器中显示内联补全（使用当前光标位置）
      showInlineAICompletion();
    }
  } catch (error) {
    console.error('AI代码补全失败:', error);
    showAICompletion.value = false;
  } finally {
    aiCompletionLoading.value = false;
  }
};

// 应用AI补全
const applyAICompletion = () => {
  console.log('applyAICompletion 被调用', {
    editor: !!editor,
    aiCompletion: aiCompletion.value
  });
  
  if (!editor || !aiCompletion.value) {
    console.log('applyAICompletion 提前返回');
    return;
  }
  
  // 获取当前光标位置
  const cursor = editor.getCursor();
  console.log('当前光标位置:', cursor);
  
  // 在光标位置插入补全内容
  editor.replaceRange(aiCompletion.value, cursor);
  console.log('补全内容已插入:', aiCompletion.value);
  
  // 更新当前代码
  currentCode.value = editor.getValue();
  
  // 保存到本地存储
  const storageKey = getStorageKey();
  localStorage.setItem(storageKey, JSON.stringify({
    code: currentCode.value,
    language: selectedLanguage.value,
    timestamp: Date.now()
  }));
  
  // 清除补全
  clearInlineAICompletion();
  showAICompletion.value = false;
  aiCompletion.value = '';
  
  console.log('AI补全应用完成');
};

// 显示内联AI补全
const showInlineAICompletion = () => {
  if (!editor || !aiCompletion.value) {
    console.log('showInlineAICompletion 提前返回');
    return;
  }
  
  // 清除之前的补全
  clearInlineAICompletion();
  
  // 获取当前光标位置
  const cursor = editor.getCursor();
  console.log('显示AI补全时的光标位置:', cursor);
  
  // 创建简单的overlay
  const overlay = document.createElement('div');
  overlay.className = 'ai-completion-overlay';
  overlay.textContent = aiCompletion.value;
  overlay.style.cssText = `
    position: fixed;
    color: #888;
    opacity: 0.6;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 14px;
    line-height: 1.4;
    pointer-events: none;
    user-select: none;
    z-index: 1000;
    white-space: pre;
    background: transparent;
    border: none;
    outline: none;
    margin: 0;
    padding: 0;
  `;
  
  // 获取光标在页面中的位置
  const coords = editor.charCoords(cursor, 'page');
  const charWidth = editor.defaultCharWidth();
  const left = coords.left + charWidth;
  const top = coords.top;
  
  overlay.style.left = left + 'px';
  overlay.style.top = top + 'px';
  
  // 添加到body
  document.body.appendChild(overlay);
  
  // 保存引用
  aiCompletionWidget.value = overlay;
  
  // 添加光标位置变化监听，自动取消补全
  let lastCursorPos = { line: cursor.line, ch: cursor.ch };
  
  const cursorPositionHandler = () => {
    const currentCursor = editor.getCursor();
    // 检查光标位置是否发生变化
    if (currentCursor.line !== lastCursorPos.line || currentCursor.ch !== lastCursorPos.ch) {
      console.log('检测到光标位置变化，自动取消AI补全', {
        from: lastCursorPos,
        to: currentCursor
      });
      cancelAICompletion();
    }
  };
  
  // 添加编辑器滚动监听，自动取消补全
  const editorScrollHandler = () => {
    console.log('检测到编辑器滚动，自动取消AI补全');
    cancelAICompletion();
  };
  
  // 添加界面滚动监听，自动取消补全
  const windowScrollHandler = () => {
    console.log('检测到界面滚动，自动取消AI补全');
    cancelAICompletion();
  };
  
  // 监听编辑器的光标活动事件
  editor.on('cursorActivity', cursorPositionHandler);
  
  // 监听编辑器的滚动事件
  editor.on('scroll', editorScrollHandler);
  
  // 监听窗口滚动事件
  window.addEventListener('scroll', windowScrollHandler);

  // 保存处理器引用，用于清理
  overlay._cursorHandler = cursorPositionHandler;
  overlay._editorScrollHandler = editorScrollHandler;
  overlay._windowScrollHandler = windowScrollHandler;
  
  console.log('AI补全显示完成，位置:', { left, top });
};

// 添加AI补全样式
const addAICompletionStyles = () => {
  if (document.getElementById('ai-completion-styles')) return;
  
  const style = document.createElement('style');
  style.id = 'ai-completion-styles';
  style.textContent = `
    .ai-completion-overlay {
      position: fixed;
      color: #888;
      opacity: 0.6;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 14px;
      line-height: 1.4;
      pointer-events: none;
      user-select: none;
      z-index: 1000;
      white-space: pre;
      background: transparent;
      border: none;
      outline: none;
      margin: 0;
      padding: 0;
    }
  `;
  document.head.appendChild(style);
};

// 清除内联AI补全
const clearInlineAICompletion = () => {
  if (aiCompletionWidget.value) {
    // 移除光标移动监听器
    if (aiCompletionWidget.value._cursorHandler) {
      editor.off('cursorActivity', aiCompletionWidget.value._cursorHandler);
    }
    // 移除编辑器滚动监听器
    if (aiCompletionWidget.value._editorScrollHandler) {
      editor.off('scroll', aiCompletionWidget.value._editorScrollHandler);
    }
    // 移除窗口滚动监听器
    if (aiCompletionWidget.value._windowScrollHandler) {
      window.removeEventListener('scroll', aiCompletionWidget.value._windowScrollHandler);
    }
    // 移除overlay
    aiCompletionWidget.value.remove();
    aiCompletionWidget.value = null;
  }
  // 清除防抖定时器
  if (aiCompletionTimeout.value) {
    clearTimeout(aiCompletionTimeout.value);
    aiCompletionTimeout.value = null;
  }
};

// 取消AI补全
const cancelAICompletion = () => {
  showAICompletion.value = false;
  aiCompletion.value = '';
  clearInlineAICompletion();
  // 清除防抖定时器
  if (aiCompletionTimeout.value) {
    clearTimeout(aiCompletionTimeout.value);
    aiCompletionTimeout.value = null;
  }
  // 确保编辑器获得焦点
  if (editor) {
    editor.focus();
    // 强制刷新编辑器状态
    editor.refresh();
  }
};

const dropdownOpen = ref(false);
const toggleDropdown = () => dropdownOpen.value = !dropdownOpen.value;
const closeDropdown = () => setTimeout(() => dropdownOpen.value = false, 200);
// const selectQuestion = (question) => currentQuestion.value = question; // 已移除重复定义
const toggleFavorite = async () => {
  if (!currentQuestion.value) return;
  
  try {
    if (currentQuestion.value.is_favorited) {
      await questionStore.unfavoriteQuestion(currentQuestion.value.id);
    } else {
      await questionStore.favoriteQuestion(currentQuestion.value.id);
    }
    // 更新本地状态
    currentQuestion.value.is_favorited = !currentQuestion.value.is_favorited;
  } catch (error) {
    console.error('收藏操作失败:', error);
  }
};

// 切换代码补全状态
const toggleCodeCompletion = () => {
  isCodeCompletionDisabled.value = !isCodeCompletionDisabled.value;
  // 保存设置到localStorage
  localStorage.setItem('codeCompletionDisabled', isCodeCompletionDisabled.value.toString());
  // 如果禁用代码补全，清除当前的AI补全
  if (isCodeCompletionDisabled.value) {
    clearInlineAICompletion();
  }
};

// 获取当前光标所在行的内容
const getCurrentLineContent = () => {
  if (!editor) return '';
  const cursor = editor.getCursor();
  return editor.getLine(cursor.line) || '';
};

// 应用代码补全
const applyCodeCompletion = (completion) => {
  if (!editor) return;
  
  const cursor = editor.getCursor();
  const line = editor.getLine(cursor.line);
  const beforeCursor = line.substring(0, cursor.ch);
  const afterCursor = line.substring(cursor.ch);
  
  // 在光标位置插入补全内容
  editor.replaceRange(completion, cursor);
  
  // 更新当前代码状态
  currentCode.value = editor.getValue();
};

// 测试用例相关方法
const initializeTestCases = (question) => {
  testCases.value = [];
  
  // 添加示例测试用例
  if (question.sample_input) {
    testCases.value.push({
      id: 'sample',
      name: '示例测试',
      input: question.sample_input,
      output: question.sample_output || '',
      status: 'pending', // pending, running, success, error
      result: '',
      error: ''
    });
  }
  
  // 添加自定义测试用例
  testCases.value.push({
    id: 'custom',
    name: '自定义测试',
    input: '',
    output: '',
    status: 'pending',
    result: '',
    error: ''
  });
  
  activeTestCaseIndex.value = 0;
};

const switchTestCase = (index) => {
  activeTestCaseIndex.value = index;
  const testCase = testCases.value[index];
  if (testCase) {
    customInput.value = testCase.input;
  }
};

const addTestCase = () => {
  if (!newTestCaseName.value.trim() || !newTestCaseInput.value.trim()) {
    alert('请输入测试用例名称和输入内容');
    return;
  }
  
  const newTestCase = {
    id: Date.now().toString(),
    name: newTestCaseName.value.trim(),
    input: newTestCaseInput.value.trim(),
    output: '',
    status: 'pending',
    result: '',
    error: ''
  };
  
  // 插入到自定义测试用例之前
  const customIndex = testCases.value.findIndex(tc => tc.id === 'custom');
  if (customIndex !== -1) {
    testCases.value.splice(customIndex, 0, newTestCase);
  } else {
    testCases.value.push(newTestCase);
  }
  
  // 清空输入
  newTestCaseName.value = '';
  newTestCaseInput.value = '';
  isAddingTestCase.value = false;
};

const removeTestCase = (index) => {
  if (testCases.value[index].id === 'sample' || testCases.value[index].id === 'custom') {
    alert('示例测试和自定义测试不能删除');
    return;
  }
  
  testCases.value.splice(index, 1);
  
  // 调整活动索引
  if (activeTestCaseIndex.value >= testCases.value.length) {
    activeTestCaseIndex.value = testCases.value.length - 1;
  }
};

const cancelAddTestCase = () => {
  newTestCaseName.value = '';
  newTestCaseInput.value = '';
  isAddingTestCase.value = false;
};

// 测试用例输入相关方法（保留兼容性）
const useSampleInput = () => {
  if (currentQuestion.value && currentQuestion.value.sample_input) {
    customInput.value = currentQuestion.value.sample_input;
  } else {
    customInput.value = '';
  }
};

const clearCustomInput = () => {
  customInput.value = '';
};

// 代码执行相关方法
const runCode = async () => {
  if (!editor) {
    alert('编辑器未初始化');
    return;
  }

  const code = editor.getValue();
  if (!code.trim()) {
    alert('请输入代码');
    return;
  }

  // 检查是否有有效的测试数据
  const hasValidTestData = testCases.value.some(testCase => {
    // 对于自定义测试用例，检查customInput是否有数据
    if (testCase.id === 'custom') {
      return customInput.value && customInput.value.trim();
    }
    // 对于其他测试用例，检查input字段
    return testCase.input && testCase.input.trim();
  });
  
  if (!hasValidTestData) {
    alert('该题目暂无测试数据，无法运行代码。请联系管理员添加测试用例。');
    return;
  }

  // 更新当前测试用例的输入（如果有修改）
  const currentTestCase = testCases.value[activeTestCaseIndex.value];
  if (currentTestCase) {
    currentTestCase.input = customInput.value;
  }

  // 设置运行状态
  isRunning.value = true;
  
  // 重置所有测试用例状态
  testCases.value.forEach(testCase => {
    testCase.status = 'pending';
    testCase.result = '';
    testCase.error = '';
  });
  
  // 清空全局输出（保持兼容性）
  runOutput.value = '';
  runError.value = '';

  // 批量测试所有测试用例
  const testResults = [];
  
  for (let i = 0; i < testCases.value.length; i++) {
    const testCase = testCases.value[i];
    
    // 跳过没有输入的测试用例
    if (!testCase.input.trim()) {
      testCase.status = 'pending';
      continue;
    }
    
    testCase.status = 'running';
    
    try {
      const response = await executionApi.runCode({
        question_id: questionId.value,
        code: code,
        language: selectedLanguage.value,
        input: testCase.input
      });

      if (response.data.status === 'success') {
        testCase.status = 'success';
        testCase.result = response.data.output;
        testCase.error = '';
        testResults.push({
          name: testCase.name,
          status: 'success',
          output: response.data.output
        });
      } else {
        testCase.status = 'error';
        testCase.result = '';
        testCase.error = response.data.error || '代码执行失败';
        testResults.push({
          name: testCase.name,
          status: 'error',
          error: response.data.error || '代码执行失败'
        });
      }
    } catch (error) {
      testCase.status = 'error';
      testCase.result = '';
      testCase.error = error.response?.data?.message || '网络请求失败';
      testResults.push({
        name: testCase.name,
        status: 'error',
        error: error.response?.data?.message || '网络请求失败'
      });
    }
  }

  // 生成汇总结果
  const successCount = testResults.filter(r => r.status === 'success').length;
  const errorCount = testResults.filter(r => r.status === 'error').length;
  
  // 更新全局输出（显示汇总结果）
  runOutput.value = `测试完成！成功: ${successCount}, 失败: ${errorCount}\n\n`;
  testResults.forEach(result => {
    if (result.status === 'success') {
      runOutput.value += `✅ ${result.name}: ${result.output}\n`;
    } else {
      runOutput.value += `❌ ${result.name}: ${result.error}\n`;
    }
  });
  
  runError.value = errorCount > 0 ? `${errorCount} 个测试用例执行失败` : '';
  
  isRunning.value = false;
};

// Toast提示函数
const showToast = (message, type = 'info') => {
  // 简单的alert实现，可以后续替换为更美观的toast组件
  if (type === 'success') {
    alert(`✅ ${message}`);
  } else if (type === 'error') {
    alert(`❌ ${message}`);
  } else {
    alert(`ℹ️ ${message}`);
  }
};

const submitCode = async () => {
  if (!editor) {
    alert('编辑器未初始化');
    return;
  }

  const code = editor.getValue();
  if (!code.trim()) {
    alert('请输入代码');
    return;
  }

  isSubmitting.value = true;

  try {
    const response = await executionApi.submitCode({
      question_id: questionId.value,
      code: code,
      language: selectedLanguage.value
    });

    // 保存提交结果到当前提交记录
    currentSubmission.value = {
      id: response.data.id,
      question_id: response.data.question_id,
      status: response.data.status,
      score: response.data.score,
      time_used: response.data.time_used,
      memory_used: response.data.memory_used,
      test_cases: response.data.test_cases,
      passed_cases: response.data.passed_cases,
      submitted_at: response.data.submitted_at,
      language: selectedLanguage.value,
      code: code
    };

    // 将新提交记录添加到提交记录列表的开头
    if (submissions.value) {
      submissions.value.unshift(currentSubmission.value);
    }

    // 切换到提交记录标签页
    activeTab.value = 'submission';
    
    // 标记已提交，启用代码补全功能
    hasSubmitted.value = true;
    
    // 重新加载提交记录列表
    await loadSubmissions();
    
    // 重新加载题目数据以更新统计数据，但不重置编辑器内容
    await loadQuestion(true);
    
  } catch (error) {
    console.error('提交失败:', error);
  } finally {
    isSubmitting.value = false;
  }
};

// 过滤逻辑
// 题目详情页面不需要搜索功能，已移除
// watch(searchQuery, (newVal) => {
//   filteredQuestions.value = newVal 
//     ? questions.value.filter(q => q.title.toLowerCase().includes(newVal.toLowerCase()))
//     : [...questions.value];
// });

watch([languageFilter, statusFilter], () => {
  // 重新加载提交记录以应用新的过滤条件
  if (activeTab.value === 'submission') {
    loadSubmissions();
  }
});

// 监听标签切换
watch(activeTab, (newTab) => {
  if (newTab === 'submission') {
    // 切换到提交记录时，加载数据
    loadSubmissions();
  } else if (newTab === 'solution') {
    // 切换到题解时，加载数据
    loadSolutions();
  } else if (newTab === 'discussion') {
    // 切换到讨论区时，加载数据
    loadDiscussions();
  }
});

</script>

<style>
@tailwind base;
@tailwind components;
@tailwind utilities;

/* 全局样式调整 */
#app, .font-inter {
  overflow: visible !important;
}

main {
  overflow: hidden !important;
}

/* 代码编辑器字体优化 */
.code-editor-container .CodeMirror {
  font-family: 'JetBrains Mono', 'Fira Code', 'Source Code Pro', 'Monaco', 'Consolas', 'Courier New', monospace !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
  font-weight: 400 !important;
  letter-spacing: 0.025em !important;
}

.code-editor-container .CodeMirror-code {
  font-variant-ligatures: common-ligatures !important;
}

.code-editor-container .CodeMirror-lines {
  padding: 12px 0 !important;
}

/* 全屏状态样式 - 占满浏览器窗口 */
.question-fullscreen .sidebar,
.question-fullscreen .code-editor-section,
.question-fullscreen .resize-handle-vertical,
.question-fullscreen .resize-handle-horizontal {
  display: none !important;
}

.code-fullscreen .sidebar,
.code-fullscreen .question-detail-section,
.code-fullscreen .resize-handle-vertical,
.code-fullscreen .resize-handle-horizontal {
  display: none !important;
}


/* 全屏时调整布局 - 占满浏览器窗口 */
.question-fullscreen .question-detail-section {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100vw !important;
  height: 100vh !important;
  z-index: 9999 !important;
  background: white !important;
}

.code-fullscreen .code-editor-section {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100vw !important;
  height: 100vh !important;
  z-index: 9999 !important;
  background: white !important;
}


.code-editor-container .CodeMirror-line {
  padding: 0 12px !important;
}

/* 代码补全器字体样式 - 与编辑器保持一致 */
.CodeMirror-hints {
  font-family: 'JetBrains Mono', 'Fira Code', 'Source Code Pro', 'Monaco', 'Consolas', 'Courier New', monospace !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
  font-weight: 400 !important;
  letter-spacing: 0.025em !important;
  max-height: 200px !important;
  border: 1px solid #e5e7eb !important;
  border-radius: 8px !important;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06) !important;
  background: white !important;
  z-index: 1000 !important;
}

.CodeMirror-hint {
  font-family: 'JetBrains Mono', 'Fira Code', 'Source Code Pro', 'Monaco', 'Consolas', 'Courier New', monospace !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
  font-weight: 400 !important;
  letter-spacing: 0.025em !important;
  padding: 8px 12px !important;
  border-bottom: 1px solid #f3f4f6 !important;
  color: #374151 !important;
}

.CodeMirror-hint:last-child {
  border-bottom: none !important;
}

.CodeMirror-hint:hover,
.CodeMirror-hint.CodeMirror-hint-active {
  background: #f3f4f6 !important;
  color: #1f2937 !important;
}

.CodeMirror-hint-match {
  font-weight: 600 !important;
  color: #3b82f6 !important;
}

/* 选择器样式优化 - 隐藏箭头并固定宽度 */
.language-selector,
.theme-selector {
  width: 80px !important;
  min-width: 80px !important;
  max-width: 80px !important;
  height: 28px !important;
  appearance: none !important;
  -webkit-appearance: none !important;
  -moz-appearance: none !important;
  background-image: none !important;
  background-repeat: no-repeat !important;
  background-position: right 8px center !important;
  padding: 4px 8px !important;
  text-overflow: ellipsis !important;
  overflow: hidden !important;
  white-space: nowrap !important;
  border: 1px solid #e5e7eb !important;
  border-radius: 6px !important;
  font-size: 12px !important;
  line-height: 1.2 !important;
  transition: all 0.2s ease !important;
  box-sizing: border-box !important;
}

.language-selector:hover,
.theme-selector:hover {
  border-color: #d1d5db !important;
  background-color: #f9fafb !important;
}

.language-selector:focus,
.theme-selector:focus {
  outline: none !important;
  box-shadow: 0 0 0 1px rgba(59, 130, 246, 0.3) !important;
  border-color: #3b82f6 !important;
}

.language-selector:active,
.theme-selector:active {
  background-color: #f3f4f6 !important;
}

/* 确保选择器内容不会溢出 */
.language-selector option,
.theme-selector option {
  padding: 4px 8px !important;
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  font-size: 12px !important;
  line-height: 1.2 !important;
}

/* 语言选项悬浮高亮为蓝色 */
.language-selector option:hover {
  background-color: #3b82f6 !important; /* Tailwind blue-500 */
  color: #ffffff !important;
}

/* 主题选项悬浮高亮为蓝色 */
.theme-selector option:hover {
  background-color: #3b82f6 !important; /* Tailwind blue-500 */
  color: #ffffff !important;
}

/* 工具栏布局稳定性 */
.editor-toolbar {
  display: flex !important;
  justify-content: space-between !important;
  align-items: center !important;
  min-height: 48px !important;
  padding: 12px !important;
  gap: 12px !important;
}

.editor-toolbar-left {
  display: flex !important;
  align-items: center !important;
  gap: 12px !important;
  flex-shrink: 0 !important;
}

.editor-toolbar-center {
  display: flex !important;
  align-items: center !important;
  gap: 12px !important;
  flex-shrink: 0 !important;
}

.editor-toolbar-right {
  display: flex !important;
  align-items: center !important;
  gap: 8px !important;
  flex-shrink: 0 !important;
}

/* 自定义工具类 */
@layer utilities {
  .content-auto {
    content-visibility: auto;
  }
  .resize-handle {
    @apply bg-gray-300 hover:bg-blue-500 transition-colors cursor-col-resize w-1 h-full;
  }
  .resize-handle-horizontal {
    @apply bg-gray-300 hover:bg-blue-500 transition-colors cursor-row-resize w-full h-1;
  }
  .btn-action {
    @apply px-3 py-1.5 rounded-md text-sm transition-all duration-200 hover:shadow-md;
  }
  .tab-item {
    @apply px-4 py-2 text-sm font-medium transition-all border-b-2 border-transparent hover:text-blue-600 hover:bg-gray-100;
  }
  .tab-item-active {
    @apply text-blue-600 border-blue-500;
  }
  .sidebar-expanded {
    width: 300px;
    left: 0;
  }
  .sidebar-collapsed {
    width: 0;
    left: -300px;
  }
  .main-content-expanded {
    margin-left: 300px;
  }
  .main-content-collapsed {
    margin-left: 0;
  }
  .toggle-btn {
    @apply fixed z-50 bg-gradient-to-r from-blue-500 to-blue-600 text-white p-3 rounded-full shadow-lg transition-all duration-300 hover:from-blue-600 hover:to-blue-700 hover:scale-105 focus:outline-none;
    top: 20px;
  }
  .toggle-btn-left {
    left: 310px;
  }
  .toggle-btn-right {
    left: 10px;
  }
  .save-toast {
    @apply fixed bottom-4 right-4 bg-gradient-to-r from-green-500 to-green-600 text-white px-6 py-3 rounded-xl shadow-xl z-50 transition-all duration-300 transform translate-y-0 opacity-100 backdrop-blur-sm;
  }
  .save-toast.hidden {
    @apply translate-y-20 opacity-0 pointer-events-none;
  }
  /* CodeMirror 样式优化 */
  .CodeMirror {
    height: 100% !important;
    font-family: 'Fira Code', monospace !important;
    font-size: 14px !important;
  }
  .CodeMirror-gutters {
    border-right: 1px solid #ddd !important;
    background-color: #f7f7f7 !important;
  }
  .CodeMirror-linenumber {
    color: #999 !important;
    padding: 0 8px !important;
  }
  /* 补全菜单样式 */
  .CodeMirror-hint {
    @apply px-2 py-1 text-sm;
  }
  .CodeMirror-hint-active {
    @apply bg-blue-500 text-white;
  }
  .CodeMirror-hints {
    @apply border border-gray-300 rounded-md shadow-lg bg-white z-50 !important;
    max-height: 200px !important;
  }
  /* 补全项类型标识 */
  .CodeMirror-hint[type="variable"]::before {
    content: "var ";
    color: #6a737d;
    font-size: 11px;
    margin-right: 4px;
  }
  .CodeMirror-hint[type="function"]::before,
  .CodeMirror-hint[type="method"]::before {
    content: "func ";
    color: #005cc5;
    font-size: 11px;
    margin-right: 4px;
  }
  .CodeMirror-hint[type="class"]::before {
    content: "class ";
    color: #22863a;
    font-size: 11px;
    margin-right: 4px;
  }
}
</style>
